upleb.uk

Public git repos — served from a NIP-34 GRASP relay at git.upleb.uk

summaryrefslogtreecommitdiff
path: root/runtime/test
diff options
context:
space:
mode:
authorJoao vitor alves <177051894+Joaovitor404silva@users.noreply.github.com>2026-11-22 15:42:01 -0300
committerJoao vitor alves <177051894+Joaovitor404silva@users.noreply.github.com>2026-11-22 17:48:57 -0300
commitfeee3e6c1fbdfc0713323bcd64935d39bb1663cb (patch)
tree8ee6ba345e312359a8820e5334e445cf9a5fd875 /runtime/test
parentf847748cc76bd3777f9c070c4034eb2fc1c04e64 (diff)
Real-shader sandbox: placed props through a translated VS/PS pair
vk_sandbox draws the props around a point with one translated game VS/PS pair chosen by signature and descriptor layout: a real camera through the VS constants, DiffuseTex albedo through the bindless set and the PS's own S#, depth, and a fly/walk/drive window. tools/sandbox.py packs the scene (tools/sandbox_scene.py), picks the pair and runs it; --check prints counts only. docs/sandbox.md has the table layout and the measurements. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01PiKMETzszqwfnV8QQyzocY
Diffstat (limited to 'runtime/test')
-rw-r--r--runtime/test/vk_sandbox.cpp734
1 files changed, 734 insertions, 0 deletions
diff --git a/runtime/test/vk_sandbox.cpp b/runtime/test/vk_sandbox.cpp
new file mode 100644
index 000000000..b5de7bd13
--- /dev/null
+++ b/runtime/test/vk_sandbox.cpp
@@ -0,0 +1,734 @@
1// Real-shader sandbox: draws a tools/sandbox_scene.py scene through two translated game shaders.
2//
3// vk_sandbox <scene.bin> <vs.spv> <ps.spv> --out <image.ppm> [--size W H] [--cam x y z yaw pitch] [--fov deg]
4// vk_sandbox <scene.bin> <vs.spv> <ps.spv> --window [--size W H] [--cam ...] [--mode fly|walk|drive] (Windows only)
5// --window --frames N --out <image.ppm>: test run, the window shows without activation and quits after N frames
6//
7// The pair (chosen by tools/sandbox.py) is a transform VS with POSITION/NORMAL/TEXCOORD inputs and a textured PS, both reading user SGPR 8:
8// a 32-bit pointer (high dword forced to 0) to one table of descriptors in the heap, laid out as the shaders load it:
9// +0x00 V# of the object constants: world rows 0..2 at 0x00/0x10/0x20, translation at 0x30
10// +0x20 T# of the albedo texture (8 dwords)
11// +0x40 V# of the view constants: light direction at 0xa0, view-projection rows at 0x160 (row-vector convention)
12// +0x60 V# of the colour constants: rgba at 0x00
13// Every draw gets its own table and object constants; view and colour constants are shared. The PS samples with the
14// S# literal in its own code, so the sampler is built from those words (gfx10::decode). Nothing here is game data:
15// the scene file and the shaders come from the user's work folder.
16//
17// Window keys (only while the window has focus): WASD move, mouse with the right button held looks, Q/E down/up,
18// Shift faster, 1 fly, 2 walk (eye 1.7 m over the ground under the camera), 3 drive (eye 1.2 m, accelerates),
19// P writes sandbox_shot.ppm, Esc quits.
20#define VK_NO_PROTOTYPES
21#ifdef _WIN32
22#define VK_USE_PLATFORM_WIN32_KHR
23#include <windows.h>
24#endif
25#include "vulkan_loader.h"
26#include "vk_device_pick.h"
27
28#include <algorithm>
29#include <array>
30#include <chrono>
31#include <cmath>
32#include <cstdio>
33#include <cstdlib>
34#include <cstring>
35#include <fstream>
36#include <string>
37#include <unordered_map>
38#include <vector>
39
40#include "../src/descriptor_table.h"
41#include "../src/gfx10_descriptors.h"
42
43static PFN_vkGetInstanceProcAddr gipa;
44#define CHECK(x) \
45 do { \
46 VkResult r_ = (x); \
47 if (r_ != VK_SUCCESS) { \
48 std::fprintf(stderr, "FAILED %s -> %d (line %d)\n", #x, r_, __LINE__); \
49 return 1; \
50 } \
51 } while (0)
52
53namespace {
54
55struct Texture { uint32_t w, h; std::vector<uint8_t> rgba; };
56struct Mesh { uint32_t first_vertex, vertex_count, first_index, index_count; };
57struct Draw { uint32_t mesh; int32_t texture; float rows[4][3]; };
58struct Scene {
59 std::vector<Texture> textures;
60 std::vector<Mesh> meshes;
61 std::vector<Draw> draws;
62 std::vector<float> vertices; // 8 floats each
63 std::vector<uint32_t> indices;
64 float center[3];
65};
66
67bool load_scene(const char* path, Scene& s) {
68 std::ifstream f(path, std::ios::binary | std::ios::ate);
69 const uint64_t file_size = f ? uint64_t(f.tellg()) : 0;
70 f.seekg(0);
71 char magic[4];
72 uint32_t hdr[4];
73 if (!f.read(magic, 4) || std::memcmp(magic, "LSB1", 4) || !f.read(reinterpret_cast<char*>(hdr), 16) ||
74 hdr[0] != 1 || !f.read(reinterpret_cast<char*>(s.center), 12))
75 return false;
76 for (uint32_t i = 0; i < hdr[1]; ++i) {
77 Texture t;
78 f.read(reinterpret_cast<char*>(&t.w), 4).read(reinterpret_cast<char*>(&t.h), 4);
79 if (!f || !t.w || !t.h || t.w > 16384 || t.h > 16384 || uint64_t(t.w) * t.h * 4 > file_size) return false;
80 t.rgba.resize(size_t(t.w) * t.h * 4);
81 f.read(reinterpret_cast<char*>(t.rgba.data()), std::streamsize(t.rgba.size()));
82 s.textures.push_back(std::move(t));
83 }
84 for (uint32_t i = 0; i < hdr[2]; ++i) {
85 uint32_t vc = 0, ic = 0;
86 f.read(reinterpret_cast<char*>(&vc), 4).read(reinterpret_cast<char*>(&ic), 4);
87 if (!f || uint64_t(vc) * 32 + uint64_t(ic) * 4 > file_size) return false;
88 Mesh m{uint32_t(s.vertices.size() / 8), vc, uint32_t(s.indices.size()), ic};
89 s.vertices.resize(s.vertices.size() + size_t(vc) * 8);
90 s.indices.resize(s.indices.size() + ic);
91 f.read(reinterpret_cast<char*>(s.vertices.data() + size_t(m.first_vertex) * 8), std::streamsize(vc) * 32);
92 f.read(reinterpret_cast<char*>(s.indices.data() + m.first_index), std::streamsize(ic) * 4);
93 if (!f) return false;
94 for (uint32_t k = 0; k < ic; ++k)
95 if (s.indices[m.first_index + k] >= vc) return false;
96 s.meshes.push_back(m);
97 }
98 for (uint32_t i = 0; i < hdr[3]; ++i) {
99 Draw d;
100 f.read(reinterpret_cast<char*>(&d), sizeof(d));
101 if (!f || d.mesh >= s.meshes.size() || d.texture >= int32_t(s.textures.size())) return false;
102 s.draws.push_back(d);
103 }
104 return bool(f);
105}
106
107std::vector<uint32_t> read_spv(const char* p) {
108 std::ifstream f(p, std::ios::binary);
109 std::vector<char> b((std::istreambuf_iterator<char>(f)), {});
110 std::vector<uint32_t> w(b.size() / 4);
111 std::memcpy(w.data(), b.data(), w.size() * 4);
112 return w;
113}
114
115struct Camera {
116 float pos[3], yaw = 0, pitch = 0, fov = 70, speed = 0;
117 int mode = 0; // 0 fly, 1 walk, 2 drive
118 void forward(float f[3]) const {
119 f[0] = std::cos(pitch) * std::cos(yaw); f[1] = std::cos(pitch) * std::sin(yaw); f[2] = std::sin(pitch);
120 }
121};
122
123// clip = wx*row0 + wy*row1 + wz*row2 + row3 (D3D clip space: y up, z 0..1), stored as 16 floats.
124void view_projection(const Camera& c, float aspect, float out[16]) {
125 float f[3]; c.forward(f);
126 float r[3] = {f[1], -f[0], 0};
127 const float rl = std::sqrt(r[0] * r[0] + r[1] * r[1]);
128 if (rl < 1e-6f) { r[0] = std::sin(c.yaw); r[1] = -std::cos(c.yaw); } else { r[0] /= rl; r[1] /= rl; }
129 const float u[3] = {r[1] * f[2] - r[2] * f[1], r[2] * f[0] - r[0] * f[2], r[0] * f[1] - r[1] * f[0]};
130 const float n = 0.1f, fa = 5000.f, sy = 1.f / std::tan(c.fov * 3.14159265f / 360.f), sx = sy / aspect;
131 const float A = fa / (fa - n), B = -n * fa / (fa - n);
132 // view = (dot(w - p, r), dot(w - p, u), dot(w - p, f)); clip = (vx*sx, vy*sy, vz*A + B, vz)
133 const float* axes[3] = {r, u, f};
134 const float scale[4] = {sx, sy, A, 1};
135 for (int k = 0; k < 4; ++k) {
136 const float* a = axes[k < 3 ? k : 2];
137 for (int j = 0; j < 3; ++j) out[j * 4 + k] = a[j] * scale[k];
138 out[12 + k] = -(a[0] * c.pos[0] + a[1] * c.pos[1] + a[2] * c.pos[2]) * scale[k] + (k == 2 ? B : 0);
139 }
140}
141
142// Ground under a point: highest scene triangle below z + 1 at (x, y), from a 4 m grid built once.
143struct Ground {
144 float cell = 4, x0 = 0, y0 = 0;
145 int nx = 0, ny = 0;
146 std::vector<std::vector<float>> tris; // per cell: 9 floats a triangle
147 void build(const Scene& s) {
148 float lo[2] = {1e30f, 1e30f}, hi[2] = {-1e30f, -1e30f};
149 std::vector<float> all;
150 for (const Draw& d : s.draws) {
151 const Mesh& m = s.meshes[d.mesh];
152 for (uint32_t i = 0; i + 2 < m.index_count; i += 3)
153 for (int k = 0; k < 3; ++k) {
154 const float* v = &s.vertices[size_t(m.first_vertex + s.indices[m.first_index + i + k]) * 8];
155 for (int j = 0; j < 3; ++j) {
156 const float w = v[0] * d.rows[0][j] + v[1] * d.rows[1][j] + v[2] * d.rows[2][j] + d.rows[3][j];
157 all.push_back(w);
158 if (j < 2) { lo[j] = std::min(lo[j], w); hi[j] = std::max(hi[j], w); }
159 }
160 }
161 }
162 if (all.empty()) return;
163 x0 = lo[0]; y0 = lo[1];
164 nx = std::min(4096, int((hi[0] - lo[0]) / cell) + 1); ny = std::min(4096, int((hi[1] - lo[1]) / cell) + 1);
165 tris.assign(size_t(nx) * ny, {});
166 for (size_t t = 0; t < all.size(); t += 9) {
167 const float* p = &all[t];
168 const float ax = std::min({p[0], p[3], p[6]}), bx = std::max({p[0], p[3], p[6]});
169 const float ay = std::min({p[1], p[4], p[7]}), by = std::max({p[1], p[4], p[7]});
170 if (bx - ax > 64 || by - ay > 64) continue; // skip huge sheets (skydomes, water planes)
171 for (int cy = std::max(0, int(std::floor((ay - y0) / cell))); cy <= std::min(ny - 1, int(std::floor((by - y0) / cell))); ++cy)
172 for (int cx = std::max(0, int(std::floor((ax - x0) / cell))); cx <= std::min(nx - 1, int(std::floor((bx - x0) / cell))); ++cx)
173 tris[size_t(cy) * nx + cx].insert(tris[size_t(cy) * nx + cx].end(), p, p + 9);
174 }
175 }
176 bool height(float x, float y, float below, float& out) const {
177 const int cx = int(std::floor((x - x0) / cell)), cy = int(std::floor((y - y0) / cell));
178 if (cx < 0 || cy < 0 || cx >= nx || cy >= ny) return false;
179 bool hit = false;
180 const auto& v = tris[size_t(cy) * nx + cx];
181 for (size_t t = 0; t < v.size(); t += 9) {
182 const float* p = &v[t];
183 const float d = (p[3] - p[0]) * (p[7] - p[1]) - (p[6] - p[0]) * (p[4] - p[1]);
184 if (std::fabs(d) < 1e-9f) continue;
185 const float a = ((p[3] - x) * (p[7] - y) - (p[6] - x) * (p[4] - y)) / d;
186 const float b = ((p[6] - x) * (p[1] - y) - (p[0] - x) * (p[7] - y)) / d;
187 const float c = 1 - a - b;
188 if (a < 0 || b < 0 || c < 0) continue;
189 const float z = a * p[2] + b * p[5] + c * p[8];
190 if (z <= below && (!hit || z > out)) { out = z; hit = true; }
191 }
192 return hit;
193 }
194};
195
196#ifdef _WIN32
197bool g_quit = false, g_look = false;
198int g_mx = 0, g_my = 0, g_dx = 0, g_dy = 0;
199LRESULT CALLBACK wndproc(HWND h, UINT m, WPARAM w, LPARAM l) {
200 switch (m) {
201 case WM_CLOSE: g_quit = true; return 0;
202 case WM_RBUTTONDOWN: g_look = true; g_mx = short(LOWORD(l)); g_my = short(HIWORD(l)); SetCapture(h); return 0;
203 case WM_RBUTTONUP: g_look = false; ReleaseCapture(); return 0;
204 case WM_MOUSEMOVE:
205 if (g_look) { const int x = short(LOWORD(l)), y = short(HIWORD(l)); g_dx += x - g_mx; g_dy += y - g_my; g_mx = x; g_my = y; }
206 return 0;
207 }
208 return DefWindowProcW(h, m, w, l);
209}
210#endif
211
212bool write_ppm(const char* path, const uint8_t* bgra_or_rgba, uint32_t w, uint32_t h, bool bgra) {
213 std::ofstream o(path, std::ios::binary);
214 o << "P6\n" << w << " " << h << "\n255\n";
215 for (size_t i = 0; i < size_t(w) * h; ++i) {
216 const uint8_t* p = bgra_or_rgba + i * 4;
217 const char px[3] = {char(p[bgra ? 2 : 0]), char(p[1]), char(p[bgra ? 0 : 2])};
218 o.write(px, 3);
219 }
220 return bool(o);
221}
222
223} // namespace
224
225int main(int argc, char** argv) {
226 if (argc < 4) {
227 std::fprintf(stderr, "usage: vk_sandbox scene.bin vs.spv ps.spv (--out image.ppm | --window) [--size W H] "
228 "[--cam x y z yaw pitch] [--fov deg]\n");
229 return 2;
230 }
231 Scene scene;
232 if (!load_scene(argv[1], scene)) { std::fprintf(stderr, "bad scene file %s\n", argv[1]); return 2; }
233 uint32_t W = 1280, H = 720;
234 const char* out_path = nullptr;
235 bool window = false;
236 int frames = 0; // --frames N: window test run, shown without activation, quits after N frames
237 Camera cam{};
238 cam.pos[0] = scene.center[0] - 40; cam.pos[1] = scene.center[1] - 40; cam.pos[2] = scene.center[2] + 25;
239 cam.yaw = 0.785398f; cam.pitch = -0.35f;
240 for (int i = 4; i < argc; ++i) {
241 if (!std::strcmp(argv[i], "--out") && i + 1 < argc) out_path = argv[++i];
242 else if (!std::strcmp(argv[i], "--window")) window = true;
243 else if (!std::strcmp(argv[i], "--frames") && i + 1 < argc) frames = std::atoi(argv[++i]);
244 else if (!std::strcmp(argv[i], "--mode") && i + 1 < argc) {
245 const char* m = argv[++i];
246 cam.mode = !std::strcmp(m, "walk") ? 1 : !std::strcmp(m, "drive") ? 2 : 0;
247 }
248 else if (!std::strcmp(argv[i], "--size") && i + 2 < argc) { W = std::atoi(argv[++i]); H = std::atoi(argv[++i]); }
249 else if (!std::strcmp(argv[i], "--fov") && i + 1 < argc) cam.fov = float(std::atof(argv[++i]));
250 else if (!std::strcmp(argv[i], "--cam") && i + 5 < argc) {
251 for (int k = 0; k < 3; ++k) cam.pos[k] = float(std::atof(argv[++i]));
252 cam.yaw = float(std::atof(argv[++i])) * 3.14159265f / 180; cam.pitch = float(std::atof(argv[++i])) * 3.14159265f / 180;
253 } else { std::fprintf(stderr, "unknown argument %s\n", argv[i]); return 2; }
254 }
255#ifndef _WIN32
256 if (window) { std::fprintf(stderr, "--window needs Windows\n"); return 2; }
257#endif
258 if (window && frames && !out_path) { std::fprintf(stderr, "--frames needs --out\n"); return 2; }
259 if (!out_path && !window) { std::fprintf(stderr, "give --out or --window\n"); return 2; }
260 std::fprintf(stderr, "scene: %zu draws, %zu meshes, %zu textures, %zu triangles\n", scene.draws.size(),
261 scene.meshes.size(), scene.textures.size(), scene.indices.size() / 3);
262
263 gipa = load_vulkan();
264 if (!gipa) { std::fprintf(stderr, "the Vulkan loader was not found\n"); return 77; }
265 VkInstance inst = VK_NULL_HANDLE;
266#define LI(n) auto n = reinterpret_cast<PFN_##n>(gipa(inst, #n))
267 LI(vkCreateInstance);
268 VkApplicationInfo app{VK_STRUCTURE_TYPE_APPLICATION_INFO}; app.apiVersion = VK_API_VERSION_1_2;
269 const char* inst_ext[2] = {"VK_KHR_surface", "VK_KHR_win32_surface"};
270 VkInstanceCreateInfo ici{VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO}; ici.pApplicationInfo = &app;
271 if (window) { ici.enabledExtensionCount = 2; ici.ppEnabledExtensionNames = inst_ext; }
272 if (vkCreateInstance(&ici, nullptr, &inst) != VK_SUCCESS) { std::fprintf(stderr, "unsupported: no Vulkan instance\n"); return 77; }
273 LI(vkEnumeratePhysicalDevices); LI(vkGetPhysicalDeviceProperties); LI(vkGetPhysicalDeviceQueueFamilyProperties);
274 LI(vkGetPhysicalDeviceMemoryProperties); LI(vkCreateDevice); LI(vkGetDeviceProcAddr);
275 uint32_t n = 0;
276 CHECK(vkEnumeratePhysicalDevices(inst, &n, nullptr));
277 if (!n) { std::fprintf(stderr, "unsupported: no Vulkan physical device\n"); return 77; }
278 std::vector<VkPhysicalDevice> pds(n);
279 CHECK(vkEnumeratePhysicalDevices(inst, &n, pds.data()));
280 VkPhysicalDevice pd = VK_NULL_HANDLE;
281 VkPhysicalDeviceProperties props{};
282 int best = -1;
283 for (auto p : pds) {
284 VkPhysicalDeviceProperties pp; vkGetPhysicalDeviceProperties(p, &pp);
285 if (int r = leonida::vk_test::device_rank(pp.deviceType, pp.vendorID); r > best) { pd = p; props = pp; best = r; }
286 }
287 constexpr uint32_t push_words = 36, push_bytes = push_words * 4;
288 if (props.limits.maxPushConstantsSize < push_bytes) { std::fprintf(stderr, "unsupported: push constants\n"); return 77; }
289 std::fprintf(stderr, "device: %s\n", props.deviceName);
290 uint32_t qn = 0; vkGetPhysicalDeviceQueueFamilyProperties(pd, &qn, nullptr);
291 std::vector<VkQueueFamilyProperties> qf(qn); vkGetPhysicalDeviceQueueFamilyProperties(pd, &qn, qf.data());
292 uint32_t qi = 0;
293 while (qi < qn && !(qf[qi].queueFlags & VK_QUEUE_GRAPHICS_BIT)) ++qi;
294 if (qi == qn) { std::fprintf(stderr, "unsupported: no graphics queue\n"); return 77; }
295
296#ifdef _WIN32
297 HWND hwnd = nullptr;
298 VkSurfaceKHR surface = VK_NULL_HANDLE;
299 if (window) {
300 WNDCLASSW wc{}; wc.lpfnWndProc = wndproc; wc.hInstance = GetModuleHandleW(nullptr); wc.lpszClassName = L"vk_sandbox";
301 wc.hCursor = LoadCursor(nullptr, IDC_ARROW);
302 RegisterClassW(&wc);
303 RECT rc{0, 0, LONG(W), LONG(H)}; AdjustWindowRect(&rc, WS_OVERLAPPEDWINDOW, FALSE);
304 hwnd = CreateWindowExW(0, L"vk_sandbox", L"Leonida real-shader sandbox", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT,
305 CW_USEDEFAULT, rc.right - rc.left, rc.bottom - rc.top, nullptr, nullptr, wc.hInstance, nullptr);
306 ShowWindow(hwnd, frames ? SW_SHOWNOACTIVATE : SW_SHOWNORMAL);
307 LI(vkCreateWin32SurfaceKHR);
308 VkWin32SurfaceCreateInfoKHR sci{VK_STRUCTURE_TYPE_WIN32_SURFACE_CREATE_INFO_KHR};
309 sci.hinstance = wc.hInstance; sci.hwnd = hwnd;
310 CHECK(vkCreateWin32SurfaceKHR(inst, &sci, nullptr, &surface));
311 }
312#endif
313
314 float prio = 1;
315 VkDeviceQueueCreateInfo qci{VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO};
316 qci.queueFamilyIndex = qi; qci.queueCount = 1; qci.pQueuePriorities = &prio;
317 VkPhysicalDeviceVulkan12Features f12{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES};
318 f12.bufferDeviceAddress = VK_TRUE; f12.runtimeDescriptorArray = VK_TRUE; f12.descriptorIndexing = VK_TRUE;
319 f12.shaderSampledImageArrayNonUniformIndexing = VK_TRUE;
320 VkPhysicalDeviceFeatures2 f2{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2}; f2.pNext = &f12;
321 f2.features.shaderInt64 = VK_TRUE;
322 const char* dev_ext[1] = {"VK_KHR_swapchain"};
323 VkDeviceCreateInfo dci{VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO};
324 dci.pNext = &f2; dci.queueCreateInfoCount = 1; dci.pQueueCreateInfos = &qci;
325 if (window) { dci.enabledExtensionCount = 1; dci.ppEnabledExtensionNames = dev_ext; }
326 VkDevice dev; CHECK(vkCreateDevice(pd, &dci, nullptr, &dev));
327#define LD(n) auto n = reinterpret_cast<PFN_##n>(vkGetDeviceProcAddr(dev, #n))
328 LD(vkGetDeviceQueue); LD(vkCreateImage); LD(vkGetImageMemoryRequirements); LD(vkAllocateMemory);
329 LD(vkBindImageMemory); LD(vkCreateImageView); LD(vkCreateRenderPass); LD(vkCreateFramebuffer);
330 LD(vkCreateShaderModule); LD(vkCreatePipelineLayout); LD(vkCreateGraphicsPipelines); LD(vkCreateCommandPool);
331 LD(vkAllocateCommandBuffers); LD(vkBeginCommandBuffer); LD(vkCmdBeginRenderPass); LD(vkCmdBindPipeline);
332 LD(vkCmdDrawIndexed); LD(vkCmdEndRenderPass); LD(vkCmdCopyImageToBuffer); LD(vkCmdCopyBufferToImage);
333 LD(vkEndCommandBuffer); LD(vkQueueSubmit); LD(vkQueueWaitIdle); LD(vkCreateBuffer); LD(vkResetCommandBuffer);
334 LD(vkGetBufferMemoryRequirements); LD(vkBindBufferMemory); LD(vkMapMemory); LD(vkGetBufferDeviceAddress);
335 LD(vkCreateSampler); LD(vkCreateDescriptorSetLayout); LD(vkCreateDescriptorPool); LD(vkAllocateDescriptorSets);
336 LD(vkUpdateDescriptorSets); LD(vkCmdBindDescriptorSets); LD(vkCmdPushConstants); LD(vkCmdPipelineBarrier);
337 LD(vkCmdBindVertexBuffers); LD(vkCmdBindIndexBuffer); LD(vkCmdBlitImage);
338 VkQueue q; vkGetDeviceQueue(dev, qi, 0, &q);
339 VkPhysicalDeviceMemoryProperties mp; vkGetPhysicalDeviceMemoryProperties(pd, &mp);
340 auto memtype = [&](uint32_t bits, VkMemoryPropertyFlags want) {
341 for (uint32_t i = 0; i < mp.memoryTypeCount; i++)
342 if ((bits & (1u << i)) && (mp.memoryTypes[i].propertyFlags & want) == want) return i;
343 return 0u;
344 };
345 auto make_buffer = [&](VkDeviceSize size, VkBufferUsageFlags usage, VkBuffer* b, void** map) {
346 VkBufferCreateInfo bi{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; bi.size = size; bi.usage = usage;
347 VkResult r = vkCreateBuffer(dev, &bi, nullptr, b); if (r) return r;
348 VkMemoryRequirements mr; vkGetBufferMemoryRequirements(dev, *b, &mr);
349 VkMemoryAllocateFlagsInfo fi{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_FLAGS_INFO}; fi.flags = VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT;
350 VkMemoryAllocateInfo ai{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO}; ai.pNext = &fi; ai.allocationSize = mr.size;
351 ai.memoryTypeIndex = memtype(mr.memoryTypeBits, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT);
352 VkDeviceMemory m; r = vkAllocateMemory(dev, &ai, nullptr, &m); if (r) return r;
353 r = vkBindBufferMemory(dev, *b, m, 0); if (r) return r;
354 return vkMapMemory(dev, m, 0, size, 0, map);
355 };
356 auto make_image = [&](uint32_t w, uint32_t h, VkFormat fmt, VkImageUsageFlags usage, VkImageAspectFlags aspect,
357 VkImage* img, VkImageView* view) {
358 VkImageCreateInfo ii{VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO};
359 ii.imageType = VK_IMAGE_TYPE_2D; ii.format = fmt; ii.extent = {w, h, 1}; ii.mipLevels = 1; ii.arrayLayers = 1;
360 ii.samples = VK_SAMPLE_COUNT_1_BIT; ii.tiling = VK_IMAGE_TILING_OPTIMAL; ii.usage = usage;
361 VkResult r = vkCreateImage(dev, &ii, nullptr, img); if (r) return r;
362 VkMemoryRequirements mr; vkGetImageMemoryRequirements(dev, *img, &mr);
363 VkMemoryAllocateInfo ai{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO}; ai.allocationSize = mr.size;
364 ai.memoryTypeIndex = memtype(mr.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT);
365 VkDeviceMemory m; r = vkAllocateMemory(dev, &ai, nullptr, &m); if (r) return r;
366 r = vkBindImageMemory(dev, *img, m, 0); if (r) return r;
367 VkImageViewCreateInfo vi{VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO};
368 vi.image = *img; vi.viewType = VK_IMAGE_VIEW_TYPE_2D; vi.format = fmt; vi.subresourceRange = {aspect, 0, 1, 0, 1};
369 return vkCreateImageView(dev, &vi, nullptr, view);
370 };
371
372 // Heap: the Xbox GPU VA window. 0x1000 view constants, 0x1200 colour constants, then 0x80 per draw: the
373 // descriptor table at +0 (0x70 bytes used) and nothing else; object constants follow all tables.
374 const uint32_t view_va = 0x1000, colour_va = 0x1200, table_va = 0x2000;
375 const uint32_t ndraw = uint32_t(scene.draws.size());
376 const uint32_t object_va = table_va + ndraw * 0x80;
377 const VkDeviceSize heap_bytes = object_va + VkDeviceSize(ndraw) * 0x40 + 0x1000;
378 VkBuffer heap; void* heapp;
379 CHECK(make_buffer(heap_bytes, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT, &heap, &heapp));
380 std::memset(heapp, 0, size_t(heap_bytes));
381 auto heap_u32 = [&](uint32_t va) { return reinterpret_cast<uint32_t*>(static_cast<char*>(heapp) + va); };
382 auto heap_f32 = [&](uint32_t va) { return reinterpret_cast<float*>(static_cast<char*>(heapp) + va); };
383 VkBufferDeviceAddressInfo bdai{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO}; bdai.buffer = heap;
384 const VkDeviceAddress heap_base = vkGetBufferDeviceAddress(dev, &bdai);
385 // A raw V#: base in word0/word1[15:0], stride 0, NUM_RECORDS bytes, OOB_SELECT 3 (raw byte range).
386 auto vsharp = [&](uint32_t at, uint32_t base, uint32_t bytes) {
387 uint32_t* p = heap_u32(at); p[0] = base; p[1] = 0; p[2] = bytes; p[3] = 3u << 28;
388 };
389 // T# keys: unique words per texture with the RGBA8 UNORM format in word 1 (the numeric type the shader reads).
390 const uint32_t fmt_word = leonida::gfx10::format_from_vulkan(VK_FORMAT_R8G8B8A8_UNORM) << 20;
391 auto tsharp = [&](uint32_t image) {
392 std::array<uint32_t, 8> t{0x5A000000u | image, fmt_word, 0x7FF7FFu, 0, 0, 0, 0, 0};
393 return t;
394 };
395 const uint32_t nimg = uint32_t(scene.textures.size()) + 1; // image 0: 1x1 white for untextured draws
396 leonida::DescriptorTable table(2 * (nimg + 2));
397 for (uint32_t i = 0; i < nimg; ++i) table.insert(tsharp(i).data(), i);
398 uint32_t ssharp[8] = {1024, 12582912, 418381824, 0, 0xFFFFFFFFu, 0xFFFFFFFFu, 0xFFFFFFFFu, 0xFFFFFFFFu}; // the PS's literal S#
399 table.insert(ssharp, 0);
400 for (uint32_t d = 0; d < ndraw; ++d) {
401 const Draw& dr = scene.draws[d];
402 const uint32_t t = table_va + d * 0x80, o = object_va + d * 0x40;
403 vsharp(t + 0x00, o, 0x40);
404 const auto ts = tsharp(dr.texture < 0 ? 0 : uint32_t(dr.texture) + 1);
405 std::memcpy(heap_u32(t + 0x20), ts.data(), 32);
406 vsharp(t + 0x40, view_va, 0x1a0);
407 vsharp(t + 0x60, colour_va, 0x10);
408 float* ob = heap_f32(o);
409 for (int r = 0; r < 4; ++r) for (int j = 0; j < 3; ++j) ob[r * 4 + j] = dr.rows[r][j];
410 }
411 float* colour = heap_f32(colour_va); colour[0] = colour[1] = colour[2] = colour[3] = 1;
412 float* light = heap_f32(view_va + 0xa0);
413 { const float l[3] = {-0.55f, -0.45f, 0.7f}; const float ln = std::sqrt(l[0] * l[0] + l[1] * l[1] + l[2] * l[2]);
414 for (int k = 0; k < 3; ++k) light[k] = l[k] / ln; }
415 const auto gpu_table = table.build_gpu_buffer(true);
416 VkBuffer tb; void* tbp;
417 CHECK(make_buffer(gpu_table.size() * 4, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, &tb, &tbp));
418 std::memcpy(tbp, gpu_table.data(), gpu_table.size() * 4);
419
420 // Geometry.
421 VkBuffer vb, ib; void* vbp; void* ibp;
422 CHECK(make_buffer(std::max<size_t>(32, scene.vertices.size() * 4), VK_BUFFER_USAGE_VERTEX_BUFFER_BIT, &vb, &vbp));
423 CHECK(make_buffer(std::max<size_t>(4, scene.indices.size() * 4), VK_BUFFER_USAGE_INDEX_BUFFER_BIT, &ib, &ibp));
424 std::memcpy(vbp, scene.vertices.data(), scene.vertices.size() * 4);
425 std::memcpy(ibp, scene.indices.data(), scene.indices.size() * 4);
426
427 // Textures.
428 std::vector<VkImage> timg(nimg); std::vector<VkImageView> tview(nimg);
429 VkDeviceSize up_bytes = 4;
430 for (const auto& t : scene.textures) up_bytes += t.rgba.size();
431 VkBuffer up; void* upp;
432 CHECK(make_buffer(up_bytes, VK_BUFFER_USAGE_TRANSFER_SRC_BIT, &up, &upp));
433 std::vector<VkDeviceSize> up_off(nimg);
434 { const uint32_t white = 0xFFFFFFFFu; std::memcpy(upp, &white, 4); VkDeviceSize at = 4;
435 for (uint32_t i = 1; i < nimg; ++i) { up_off[i] = at; std::memcpy(static_cast<char*>(upp) + at, scene.textures[i - 1].rgba.data(), scene.textures[i - 1].rgba.size()); at += scene.textures[i - 1].rgba.size(); } }
436 for (uint32_t i = 0; i < nimg; ++i)
437 CHECK(make_image(i ? scene.textures[i - 1].w : 1, i ? scene.textures[i - 1].h : 1, VK_FORMAT_R8G8B8A8_UNORM,
438 VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT, VK_IMAGE_ASPECT_COLOR_BIT, &timg[i], &tview[i]));
439 VkSamplerCreateInfo sci = leonida::gfx10::vulkan_sampler(leonida::gfx10::decode(
440 leonida::gfx10::SamplerWords{ssharp[0], ssharp[1], ssharp[2], ssharp[3]}));
441 sci.maxLod = 0; // the scene stores mip 0 only
442 VkSampler smp; CHECK(vkCreateSampler(dev, &sci, nullptr, &smp));
443
444 // Targets: RGBA8 colour + D32 depth.
445 const VkFormat cfmt = VK_FORMAT_R8G8B8A8_UNORM, dfmt = VK_FORMAT_D32_SFLOAT;
446 VkImage rt, dt; VkImageView rtv, dtv;
447 CHECK(make_image(W, H, cfmt, VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT, VK_IMAGE_ASPECT_COLOR_BIT, &rt, &rtv));
448 CHECK(make_image(W, H, dfmt, VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT, VK_IMAGE_ASPECT_DEPTH_BIT, &dt, &dtv));
449 VkAttachmentDescription ad[2]{};
450 ad[0].format = cfmt; ad[0].samples = VK_SAMPLE_COUNT_1_BIT; ad[0].loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
451 ad[0].storeOp = VK_ATTACHMENT_STORE_OP_STORE; ad[0].stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
452 ad[0].stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
453 ad[0].initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; ad[0].finalLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;
454 ad[1] = ad[0]; ad[1].format = dfmt; ad[1].storeOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
455 ad[1].finalLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
456 VkAttachmentReference car{0, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL}, dar{1, VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL};
457 VkSubpassDescription sd{}; sd.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;
458 sd.colorAttachmentCount = 1; sd.pColorAttachments = &car; sd.pDepthStencilAttachment = &dar;
459 VkSubpassDependency dep{0, VK_SUBPASS_EXTERNAL, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT,
460 VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, VK_ACCESS_TRANSFER_READ_BIT};
461 VkRenderPassCreateInfo rpi{VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO};
462 rpi.attachmentCount = 2; rpi.pAttachments = ad; rpi.subpassCount = 1; rpi.pSubpasses = &sd;
463 rpi.dependencyCount = 1; rpi.pDependencies = &dep;
464 VkRenderPass rp; CHECK(vkCreateRenderPass(dev, &rpi, nullptr, &rp));
465 VkImageView fbv[2] = {rtv, dtv};
466 VkFramebufferCreateInfo fbi{VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO};
467 fbi.renderPass = rp; fbi.attachmentCount = 2; fbi.pAttachments = fbv; fbi.width = W; fbi.height = H; fbi.layers = 1;
468 VkFramebuffer fb; CHECK(vkCreateFramebuffer(dev, &fbi, nullptr, &fb));
469
470 // Descriptor set: binding 0 images[], 1 samplers[], 2 the descriptor hash table.
471 VkDescriptorSetLayoutBinding b[3]{};
472 b[0] = {0, VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, nimg, VK_SHADER_STAGE_FRAGMENT_BIT | VK_SHADER_STAGE_VERTEX_BIT, nullptr};
473 b[1] = {1, VK_DESCRIPTOR_TYPE_SAMPLER, 1, VK_SHADER_STAGE_FRAGMENT_BIT | VK_SHADER_STAGE_VERTEX_BIT, nullptr};
474 b[2] = {2, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1, VK_SHADER_STAGE_FRAGMENT_BIT | VK_SHADER_STAGE_VERTEX_BIT, nullptr};
475 VkDescriptorSetLayoutCreateInfo dli{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO}; dli.bindingCount = 3; dli.pBindings = b;
476 VkDescriptorSetLayout dsl; CHECK(vkCreateDescriptorSetLayout(dev, &dli, nullptr, &dsl));
477 VkDescriptorPoolSize ps[3]{{VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, nimg}, {VK_DESCRIPTOR_TYPE_SAMPLER, 1}, {VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1}};
478 VkDescriptorPoolCreateInfo dpi{VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO}; dpi.maxSets = 1; dpi.poolSizeCount = 3; dpi.pPoolSizes = ps;
479 VkDescriptorPool dp; CHECK(vkCreateDescriptorPool(dev, &dpi, nullptr, &dp));
480 VkDescriptorSetAllocateInfo dai{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO}; dai.descriptorPool = dp; dai.descriptorSetCount = 1; dai.pSetLayouts = &dsl;
481 VkDescriptorSet ds; CHECK(vkAllocateDescriptorSets(dev, &dai, &ds));
482 std::vector<VkDescriptorImageInfo> iinfo(nimg);
483 for (uint32_t i = 0; i < nimg; ++i) iinfo[i] = {VK_NULL_HANDLE, tview[i], VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL};
484 VkDescriptorImageInfo sinfo{smp};
485 VkDescriptorBufferInfo tinfo{tb, 0, VK_WHOLE_SIZE};
486 VkWriteDescriptorSet wr[3]{};
487 for (auto& w : wr) { w.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; w.dstSet = ds; }
488 wr[0].dstBinding = 0; wr[0].descriptorCount = nimg; wr[0].descriptorType = VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE; wr[0].pImageInfo = iinfo.data();
489 wr[1].dstBinding = 1; wr[1].descriptorCount = 1; wr[1].descriptorType = VK_DESCRIPTOR_TYPE_SAMPLER; wr[1].pImageInfo = &sinfo;
490 wr[2].dstBinding = 2; wr[2].descriptorCount = 1; wr[2].descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; wr[2].pBufferInfo = &tinfo;
491 vkUpdateDescriptorSets(dev, 3, wr, 0, nullptr);
492
493 // Pipeline: the translated VS and PS, vertices (pos, normal, uv) at locations 0..2, depth test, no culling.
494 auto module = [&](const char* p, VkShaderModule* m) {
495 auto code = read_spv(p);
496 if (code.empty()) { std::fprintf(stderr, "cannot read %s\n", p); return VK_ERROR_INITIALIZATION_FAILED; }
497 VkShaderModuleCreateInfo smi{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; smi.codeSize = code.size() * 4; smi.pCode = code.data();
498 return vkCreateShaderModule(dev, &smi, nullptr, m);
499 };
500 VkShaderModule vs, fs; CHECK(module(argv[2], &vs)); CHECK(module(argv[3], &fs));
501 VkPipelineShaderStageCreateInfo st[2]{{VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}, {VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}};
502 st[0].stage = VK_SHADER_STAGE_VERTEX_BIT; st[0].module = vs; st[0].pName = "main";
503 st[1].stage = VK_SHADER_STAGE_FRAGMENT_BIT; st[1].module = fs; st[1].pName = "main";
504 VkPushConstantRange pcr{VK_SHADER_STAGE_FRAGMENT_BIT | VK_SHADER_STAGE_VERTEX_BIT, 0, push_bytes};
505 VkPipelineLayoutCreateInfo pli{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO};
506 pli.setLayoutCount = 1; pli.pSetLayouts = &dsl; pli.pushConstantRangeCount = 1; pli.pPushConstantRanges = &pcr;
507 VkPipelineLayout pl; CHECK(vkCreatePipelineLayout(dev, &pli, nullptr, &pl));
508 VkVertexInputBindingDescription vbd{0, 32, VK_VERTEX_INPUT_RATE_VERTEX};
509 VkVertexInputAttributeDescription vad[3]{{0, 0, VK_FORMAT_R32G32B32_SFLOAT, 0}, {1, 0, VK_FORMAT_R32G32B32_SFLOAT, 12},
510 {2, 0, VK_FORMAT_R32G32_SFLOAT, 24}};
511 VkPipelineVertexInputStateCreateInfo vin{VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO};
512 vin.vertexBindingDescriptionCount = 1; vin.pVertexBindingDescriptions = &vbd;
513 vin.vertexAttributeDescriptionCount = 3; vin.pVertexAttributeDescriptions = vad;
514 VkPipelineInputAssemblyStateCreateInfo ia{VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO}; ia.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST;
515 // D3D clip space has y up: a negative-height viewport (Vulkan 1.1) keeps the game's matrices unchanged.
516 VkViewport vp{0, float(H), float(W), -float(H), 0, 1}; VkRect2D sc{{0, 0}, {W, H}};
517 VkPipelineViewportStateCreateInfo vps{VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO};
518 vps.viewportCount = 1; vps.pViewports = &vp; vps.scissorCount = 1; vps.pScissors = &sc;
519 VkPipelineRasterizationStateCreateInfo rs{VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO}; rs.cullMode = VK_CULL_MODE_NONE; rs.lineWidth = 1;
520 VkPipelineMultisampleStateCreateInfo ms{VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO}; ms.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT;
521 VkPipelineDepthStencilStateCreateInfo dss{VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO};
522 dss.depthTestEnable = VK_TRUE; dss.depthWriteEnable = VK_TRUE; dss.depthCompareOp = VK_COMPARE_OP_LESS;
523 VkPipelineColorBlendAttachmentState cba{}; cba.colorWriteMask = 0xF;
524 VkPipelineColorBlendStateCreateInfo cb{VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO}; cb.attachmentCount = 1; cb.pAttachments = &cba;
525 VkGraphicsPipelineCreateInfo gpi{VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO};
526 gpi.stageCount = 2; gpi.pStages = st; gpi.pVertexInputState = &vin; gpi.pInputAssemblyState = &ia; gpi.pViewportState = &vps;
527 gpi.pRasterizationState = &rs; gpi.pMultisampleState = &ms; gpi.pDepthStencilState = &dss; gpi.pColorBlendState = &cb;
528 gpi.layout = pl; gpi.renderPass = rp;
529 VkPipeline pipe; CHECK(vkCreateGraphicsPipelines(dev, VK_NULL_HANDLE, 1, &gpi, nullptr, &pipe));
530
531 VkCommandPoolCreateInfo cpi{VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO}; cpi.queueFamilyIndex = qi;
532 cpi.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT;
533 VkCommandPool pool; CHECK(vkCreateCommandPool(dev, &cpi, nullptr, &pool));
534 VkCommandBufferAllocateInfo cai{VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO}; cai.commandPool = pool; cai.commandBufferCount = 1;
535 VkCommandBuffer cmd; CHECK(vkAllocateCommandBuffers(dev, &cai, &cmd));
536 auto barrier = [&](VkImage img, VkImageLayout from, VkImageLayout to, VkAccessFlags sa, VkAccessFlags da,
537 VkPipelineStageFlags ss, VkPipelineStageFlags dst) {
538 VkImageMemoryBarrier ib{VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER};
539 ib.oldLayout = from; ib.newLayout = to; ib.image = img; ib.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1};
540 ib.srcAccessMask = sa; ib.dstAccessMask = da; ib.srcQueueFamilyIndex = ib.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
541 vkCmdPipelineBarrier(cmd, ss, dst, 0, 0, nullptr, 0, nullptr, 1, &ib);
542 };
543 auto submit = [&]() { VkSubmitInfo si{VK_STRUCTURE_TYPE_SUBMIT_INFO}; si.commandBufferCount = 1; si.pCommandBuffers = &cmd;
544 VkResult r = vkQueueSubmit(q, 1, &si, VK_NULL_HANDLE); return r ? r : vkQueueWaitIdle(q); };
545 { // Upload the textures once.
546 VkCommandBufferBeginInfo cbi{VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO}; CHECK(vkBeginCommandBuffer(cmd, &cbi));
547 for (uint32_t i = 0; i < nimg; ++i) {
548 barrier(timg[i], VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 0, VK_ACCESS_TRANSFER_WRITE_BIT,
549 VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT);
550 VkBufferImageCopy c{}; c.bufferOffset = up_off[i]; c.imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1};
551 c.imageExtent = {i ? scene.textures[i - 1].w : 1, i ? scene.textures[i - 1].h : 1, 1};
552 vkCmdCopyBufferToImage(cmd, up, timg[i], VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &c);
553 barrier(timg[i], VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, VK_ACCESS_TRANSFER_WRITE_BIT,
554 VK_ACCESS_SHADER_READ_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT);
555 }
556 CHECK(vkEndCommandBuffer(cmd)); CHECK(submit());
557 }
558 // Records the scene into rt (left in TRANSFER_SRC_OPTIMAL). The caller ends and submits.
559 auto record = [&]() {
560 view_projection(cam, float(W) / float(H), heap_f32(view_va + 0x160));
561 VkClearValue clear[2]{}; clear[0].color = {{0.55f, 0.68f, 0.85f, 1}}; clear[1].depthStencil = {1, 0};
562 VkRenderPassBeginInfo rbi{VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO};
563 rbi.renderPass = rp; rbi.framebuffer = fb; rbi.renderArea = sc; rbi.clearValueCount = 2; rbi.pClearValues = clear;
564 vkCmdBeginRenderPass(cmd, &rbi, VK_SUBPASS_CONTENTS_INLINE);
565 vkCmdBindPipeline(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, pipe);
566 vkCmdBindDescriptorSets(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, pl, 0, 1, &ds, 0, nullptr);
567 VkDeviceSize zero = 0;
568 vkCmdBindVertexBuffers(cmd, 0, 1, &vb, &zero);
569 vkCmdBindIndexBuffer(cmd, ib, 0, VK_INDEX_TYPE_UINT32);
570 uint32_t pc[push_words] = {};
571 pc[32] = uint32_t(heap_base); pc[33] = uint32_t(heap_base >> 32);
572 for (uint32_t d = 0; d < ndraw; ++d) {
573 const Mesh& m = scene.meshes[scene.draws[d].mesh];
574 pc[8] = table_va + d * 0x80; // s8: the descriptor table; s9 (the PS's M0) stays 0
575 vkCmdPushConstants(cmd, pl, VK_SHADER_STAGE_FRAGMENT_BIT | VK_SHADER_STAGE_VERTEX_BIT, 0, push_bytes, pc);
576 vkCmdDrawIndexed(cmd, m.index_count, 1, m.first_index, int32_t(m.first_vertex), 0);
577 }
578 vkCmdEndRenderPass(cmd);
579 };
580 VkBuffer rb; void* rbp;
581 CHECK(make_buffer(VkDeviceSize(W) * H * 4, VK_BUFFER_USAGE_TRANSFER_DST_BIT, &rb, &rbp));
582 auto read_back = [&]() {
583 VkBufferImageCopy rc{}; rc.imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}; rc.imageExtent = {W, H, 1};
584 vkCmdCopyImageToBuffer(cmd, rt, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, rb, 1, &rc);
585 };
586
587 if (!window) {
588 VkCommandBufferBeginInfo cbi{VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO}; CHECK(vkBeginCommandBuffer(cmd, &cbi));
589 record(); read_back();
590 CHECK(vkEndCommandBuffer(cmd)); CHECK(submit());
591 if (!write_ppm(out_path, static_cast<const uint8_t*>(rbp), W, H, false)) { std::fprintf(stderr, "cannot write %s\n", out_path); return 1; }
592 // Coverage: pixels that differ from the clear colour were written by the translated PS.
593 const uint8_t* px = static_cast<const uint8_t*>(rbp);
594 const uint8_t clear_px[3] = {uint8_t(0.55f * 255 + 0.5f), uint8_t(0.68f * 255 + 0.5f), uint8_t(0.85f * 255 + 0.5f)};
595 size_t covered = 0;
596 for (size_t i = 0; i < size_t(W) * H; ++i)
597 covered += std::abs(px[i * 4] - clear_px[0]) > 1 || std::abs(px[i * 4 + 1] - clear_px[1]) > 1 || std::abs(px[i * 4 + 2] - clear_px[2]) > 1;
598 std::printf("vk_sandbox: %u draws, %zu of %u pixels covered -> %s\n", ndraw, covered, W * H, out_path);
599 return 0;
600 }
601
602#ifdef _WIN32
603 LI(vkGetPhysicalDeviceSurfaceCapabilitiesKHR); LI(vkGetPhysicalDeviceSurfaceFormatsKHR); LI(vkGetPhysicalDeviceSurfaceSupportKHR);
604 LD(vkCreateSwapchainKHR); LD(vkDestroySwapchainKHR); LD(vkGetSwapchainImagesKHR); LD(vkAcquireNextImageKHR);
605 LD(vkQueuePresentKHR); LD(vkCreateSemaphore);
606 VkBool32 can_present = VK_FALSE; vkGetPhysicalDeviceSurfaceSupportKHR(pd, qi, surface, &can_present);
607 if (!can_present) { std::fprintf(stderr, "the graphics queue cannot present\n"); return 1; }
608 uint32_t nf = 0; vkGetPhysicalDeviceSurfaceFormatsKHR(pd, surface, &nf, nullptr);
609 std::vector<VkSurfaceFormatKHR> sfs(nf); vkGetPhysicalDeviceSurfaceFormatsKHR(pd, surface, &nf, sfs.data());
610 if (sfs.empty()) { std::fprintf(stderr, "the surface has no formats\n"); return 1; }
611 VkSurfaceFormatKHR sf = sfs[0]; // a UNORM format keeps the blit byte-exact with the headless render
612 for (const VkSurfaceFormatKHR& c : sfs)
613 if (c.format == VK_FORMAT_B8G8R8A8_UNORM || c.format == VK_FORMAT_R8G8B8A8_UNORM) { sf = c; break; }
614 VkSwapchainCreateInfoKHR swi{VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR};
615 VkSwapchainKHR swap = VK_NULL_HANDLE;
616 std::vector<VkImage> simg;
617 // (Re)creates the swapchain for the window's current size; false while it is minimised (extent 0).
618 auto make_swap = [&]() -> int {
619 VkSurfaceCapabilitiesKHR caps;
620 if (vkGetPhysicalDeviceSurfaceCapabilitiesKHR(pd, surface, &caps) != VK_SUCCESS) return -1;
621 if (!(caps.supportedUsageFlags & VK_IMAGE_USAGE_TRANSFER_DST_BIT)) return -1;
622 const VkExtent2D ext = caps.currentExtent.width != 0xFFFFFFFFu ? caps.currentExtent : VkExtent2D{W, H};
623 if (!ext.width || !ext.height) return 0;
624 vkQueueWaitIdle(q);
625 swi.surface = surface; swi.minImageCount = std::max(2u, caps.minImageCount);
626 if (caps.maxImageCount) swi.minImageCount = std::min(swi.minImageCount, caps.maxImageCount);
627 swi.imageFormat = sf.format; swi.imageColorSpace = sf.colorSpace; swi.imageExtent = ext;
628 swi.imageArrayLayers = 1; swi.imageUsage = VK_IMAGE_USAGE_TRANSFER_DST_BIT; swi.preTransform = caps.currentTransform;
629 swi.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR; swi.presentMode = VK_PRESENT_MODE_FIFO_KHR; swi.clipped = VK_TRUE;
630 swi.oldSwapchain = swap;
631 VkSwapchainKHR next;
632 if (vkCreateSwapchainKHR(dev, &swi, nullptr, &next) != VK_SUCCESS) return -1;
633 if (swap) vkDestroySwapchainKHR(dev, swap, nullptr);
634 swap = next;
635 uint32_t ns = 0; vkGetSwapchainImagesKHR(dev, swap, &ns, nullptr);
636 simg.resize(ns); vkGetSwapchainImagesKHR(dev, swap, &ns, simg.data());
637 return 1;
638 };
639 if (make_swap() < 0) { std::fprintf(stderr, "cannot create a swapchain (TRANSFER_DST unsupported?)\n"); return 1; }
640 VkSemaphoreCreateInfo semi{VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO};
641 VkSemaphore acquired; CHECK(vkCreateSemaphore(dev, &semi, nullptr, &acquired));
642 Ground ground; ground.build(scene);
643 auto last = std::chrono::steady_clock::now();
644 bool shot_held = false;
645 int frame = 0;
646 while (!g_quit) {
647 MSG msg;
648 while (PeekMessageW(&msg, nullptr, 0, 0, PM_REMOVE)) { TranslateMessage(&msg); DispatchMessageW(&msg); }
649 const auto now = std::chrono::steady_clock::now();
650 const float dt = std::min(0.1f, std::chrono::duration<float>(now - last).count()); last = now;
651 const bool focus = GetForegroundWindow() == hwnd;
652 auto key = [&](int vk) { return focus && (GetAsyncKeyState(vk) & 0x8000); };
653 if (key(VK_ESCAPE)) break;
654 if (key('1')) cam.mode = 0; if (key('2')) cam.mode = 1; if (key('3')) cam.mode = 2;
655 cam.yaw -= g_dx * 0.004f; cam.pitch = std::clamp(cam.pitch - g_dy * 0.004f, -1.5f, 1.5f); g_dx = g_dy = 0;
656 float f[3]; cam.forward(f);
657 const float r[2] = {std::sin(cam.yaw), -std::cos(cam.yaw)};
658 const float fwd = float(key('W')) - float(key('S')), side = float(key('D')) - float(key('A'));
659 if (cam.mode == 0) {
660 const float v = (key(VK_SHIFT) ? 60.f : 12.f) * dt;
661 for (int k = 0; k < 3; ++k) cam.pos[k] += f[k] * fwd * v;
662 cam.pos[0] += r[0] * side * v; cam.pos[1] += r[1] * side * v;
663 cam.pos[2] += (float(key('E')) - float(key('Q'))) * v;
664 } else {
665 const float h = std::hypot(f[0], f[1]) > 1e-4f ? std::hypot(f[0], f[1]) : 1;
666 if (cam.mode == 1) cam.speed = fwd * (key(VK_SHIFT) ? 7.f : 2.5f);
667 else { cam.speed += fwd * 12.f * dt; cam.speed *= std::pow(0.6f, dt); cam.yaw -= side * dt * std::clamp(cam.speed / 10.f, -1.f, 1.f); }
668 cam.pos[0] += f[0] / h * cam.speed * dt; cam.pos[1] += f[1] / h * cam.speed * dt;
669 if (cam.mode == 1) { cam.pos[0] += r[0] * side * 2.5f * dt; cam.pos[1] += r[1] * side * 2.5f * dt; }
670 const float eye = cam.mode == 1 ? 1.7f : 1.2f;
671 float gz;
672 if (ground.height(cam.pos[0], cam.pos[1], cam.pos[2] - eye + 0.6f, gz)) cam.pos[2] = gz + eye;
673 }
674 uint32_t idx = 0;
675 if (!swap) { // minimised at start or since the last resize
676 const int made = make_swap();
677 if (made < 0) { std::fprintf(stderr, "cannot recreate the swapchain\n"); return 1; }
678 if (!made) { Sleep(50); continue; }
679 }
680 const VkResult acq = vkAcquireNextImageKHR(dev, swap, UINT64_MAX, acquired, VK_NULL_HANDLE, &idx);
681 if (acq == VK_ERROR_OUT_OF_DATE_KHR) {
682 const int made = make_swap();
683 if (made < 0) { std::fprintf(stderr, "cannot recreate the swapchain\n"); return 1; }
684 if (!made) { vkDestroySwapchainKHR(dev, swap, nullptr); swap = VK_NULL_HANDLE; Sleep(50); }
685 continue;
686 }
687 if (acq != VK_SUCCESS && acq != VK_SUBOPTIMAL_KHR) { std::fprintf(stderr, "vkAcquireNextImageKHR failed (%d)\n", int(acq)); return 1; }
688 CHECK(vkResetCommandBuffer(cmd, 0));
689 VkCommandBufferBeginInfo cbi{VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO}; CHECK(vkBeginCommandBuffer(cmd, &cbi));
690 record();
691 const bool last_frame = frames && ++frame >= frames;
692 const bool shot = (key('P') && !shot_held) || last_frame; shot_held = key('P');
693 if (shot) read_back();
694 barrier(simg[idx], VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 0, VK_ACCESS_TRANSFER_WRITE_BIT,
695 VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT);
696 VkImageBlit bl{}; bl.srcSubresource = bl.dstSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1};
697 bl.srcOffsets[1] = {int32_t(W), int32_t(H), 1};
698 bl.dstOffsets[1] = {int32_t(swi.imageExtent.width), int32_t(swi.imageExtent.height), 1};
699 vkCmdBlitImage(cmd, rt, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, simg[idx], VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &bl, VK_FILTER_LINEAR);
700 barrier(simg[idx], VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_LAYOUT_PRESENT_SRC_KHR, VK_ACCESS_TRANSFER_WRITE_BIT, 0,
701 VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT);
702 CHECK(vkEndCommandBuffer(cmd));
703 VkPipelineStageFlags wait_stage = VK_PIPELINE_STAGE_TRANSFER_BIT;
704 VkSubmitInfo si{VK_STRUCTURE_TYPE_SUBMIT_INFO}; si.waitSemaphoreCount = 1; si.pWaitSemaphores = &acquired;
705 si.pWaitDstStageMask = &wait_stage; si.commandBufferCount = 1; si.pCommandBuffers = &cmd;
706 CHECK(vkQueueSubmit(q, 1, &si, VK_NULL_HANDLE)); CHECK(vkQueueWaitIdle(q));
707 if (shot) {
708 const char* path = last_frame ? out_path : "sandbox_shot.ppm";
709 if (!write_ppm(path, static_cast<const uint8_t*>(rbp), W, H, false)) {
710 std::fprintf(stderr, "cannot write %s\n", path);
711 if (last_frame) return 1;
712 }
713 }
714 VkPresentInfoKHR pi{VK_STRUCTURE_TYPE_PRESENT_INFO_KHR}; pi.swapchainCount = 1; pi.pSwapchains = &swap; pi.pImageIndices = &idx;
715 const VkResult pres = vkQueuePresentKHR(q, &pi);
716 if ((pres == VK_ERROR_OUT_OF_DATE_KHR || pres == VK_SUBOPTIMAL_KHR || acq == VK_SUBOPTIMAL_KHR) && !last_frame) {
717 const int made = make_swap();
718 if (made < 0) { std::fprintf(stderr, "cannot recreate the swapchain\n"); return 1; }
719 if (!made) { vkDestroySwapchainKHR(dev, swap, nullptr); swap = VK_NULL_HANDLE; }
720 }
721 char title[160];
722 std::snprintf(title, sizeof title, "Leonida real-shader sandbox [%s] %.0f %.0f %.0f %.0f fps", cam.mode == 0 ? "fly" : cam.mode == 1 ? "walk" : "drive",
723 cam.pos[0], cam.pos[1], cam.pos[2], 1.f / std::max(dt, 1e-4f));
724 SetWindowTextA(hwnd, title);
725 if (last_frame) {
726 std::printf("vk_sandbox: window ran %d frames -> %s, camera %.2f %.2f %.2f\n", frame, out_path,
727 cam.pos[0], cam.pos[1], cam.pos[2]);
728 break;
729 }
730 }
731 vkQueueWaitIdle(q);
732#endif
733 return 0;
734}