upleb.uk

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

summaryrefslogtreecommitdiff
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
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
-rw-r--r--docs/README.md1
-rw-r--r--docs/sandbox.md86
-rw-r--r--runtime/CMakeLists.txt2
-rw-r--r--runtime/test/vk_sandbox.cpp734
-rw-r--r--tests/test_sandbox_pick.py109
-rw-r--r--tests/test_sandbox_scene.py97
-rw-r--r--tools/sandbox.py169
-rw-r--r--tools/sandbox_scene.py176
8 files changed, 1373 insertions, 1 deletions
diff --git a/docs/README.md b/docs/README.md
index 5eff8e3c1..f8dcfd0c3 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -73,6 +73,7 @@ method, scope and caveats. No game data is included.
73| [fspx.md](fspx.md) | `FSPX`, the FidelityFX DLL's native compute programs (its shaders' `ACCC` part): directory as the DLL reads it, kind-0 dispatch state, the hash prologue, `gfx1030` for its `v_dot4` code; 13 of 29 translate with `tools/fspx_unpack.py`. | 73| [fspx.md](fspx.md) | `FSPX`, the FidelityFX DLL's native compute programs (its shaders' `ACCC` part): directory as the DLL reads it, kind-0 dispatch state, the hash prologue, `gfx1030` for its `v_dot4` code; 13 of 29 translate with `tools/fspx_unpack.py`. |
74| [first_light.md](first_light.md) | The first draw of a real game model with its own translated VS/PS on a GPU: 4,213 vertices / 7,968 triangles, 78.1% coverage on an RTX 2060 SUPER; `tools/first_light.py`, the `vk_harness` mesh mode, and the same draw through the D3D12 layer (`d3d12_first_light`). | 74| [first_light.md](first_light.md) | The first draw of a real game model with its own translated VS/PS on a GPU: 4,213 vertices / 7,968 triangles, 78.1% coverage on an RTX 2060 SUPER; `tools/first_light.py`, the `vk_harness` mesh mode, and the same draw through the D3D12 layer (`d3d12_first_light`). |
75| [embedded_shaders.md](embedded_shaders.md) | DXBC containers embedded in the package's DLLs: 52 in `XboxBvhBuilder.dll` (console `FSSM` via the `XDAT`/`XBCH` record; 51/52 pass `spirv-val` today) and 29 `ACCC`/`FSPX` in the FidelityFX upscaler; the scan/extract tool and the one rule still missing. | 75| [embedded_shaders.md](embedded_shaders.md) | DXBC containers embedded in the package's DLLs: 52 in `XboxBvhBuilder.dll` (console `FSSM` via the `XDAT`/`XBCH` record; 51/52 pass `spirv-val` today) and 29 `ACCC`/`FSPX` in the FidelityFX upscaler; the scan/extract tool and the one rule still missing. |
76| [sandbox.md](sandbox.md) | Placed world props through one translated VS/PS pair with a real camera, TTPF albedo and the game's sampler: 442 of 446 draws textured; fly/walk/drive window, `tools/sandbox.py --check`. |
76| [coder.md](coder.md) | The compressed mass in `story000_script.rpf`: entry framing (`align16(entry+8)` payload), the 32-value tag alphabet, deflate-shaped but proprietary, variable-length 7/8-bit LSB-first codes with no stored table, and the `n7 = 116..127` search that finishes it. | 77| [coder.md](coder.md) | The compressed mass in `story000_script.rpf`: entry framing (`align16(entry+8)` payload), the 32-value tag alphabet, deflate-shaped but proprietary, variable-length 7/8-bit LSB-first codes with no stored table, and the `n7 = 116..127` search that finishes it. |
77| [mission_logic.md](mission_logic.md) | Mission state tables: 0x20 record layout (band counter, byte offsets), the 64-byte pool element with world transforms, case-folding joaat keys, 53.5 % of states named, 113 state-set clusters covering 82.4 % of files. | 78| [mission_logic.md](mission_logic.md) | Mission state tables: 0x20 record layout (band counter, byte offsets), the 64-byte pool element with world transforms, case-folding joaat keys, 53.5 % of states named, 113 state-set clusters covering 82.4 % of files. |
78 79
diff --git a/docs/sandbox.md b/docs/sandbox.md
new file mode 100644
index 000000000..e86fdfe81
--- /dev/null
+++ b/docs/sandbox.md
@@ -0,0 +1,86 @@
1# Real-shader sandbox: placed props through the game's own translated shaders
2
3Follows [first_light.md](first_light.md) §5: a real camera through a vertex shader's constants, a TTPF albedo
4through the bindless set with the game's sampler, and many placed world props instead of one model. Measured on
52026-11-22 from one retail Xbox Series install (1.0.2.1), on an NVIDIA GeForce RTX 4070 Ti SUPER (driver 621.24).
6Nothing below reproduces game data; every number is a count.
7
8## 1. What runs
9
10`tools/sandbox.py` packs the props around a point (`tools/sandbox_scene.py`), picks one translated VS/PS pair from
11the work folder and runs `runtime/test/vk_sandbox`, which draws every prop with that pair: vertex buffers at
12locations 0–2 (position, normal, UV), a D32 depth buffer, one indexed draw per mesh and one descriptor table per
13draw. `--window` opens a window to fly, walk or drive through the scene; `--check` renders one frame headless and
14prints only counts.
15
16The shaders are not stand-ins: the VS transforms each vertex with the world rows and view-projection it loads from
17the heap and lights it with its own `max(0.25, n·l)`; the PS samples the albedo through the T# it loads and the
18S# literal in its code, and multiplies by the VS colour. Lighting beyond that, shadows and the G-buffer passes are
19not part of this pair.
20
21## 2. How the pair is chosen
22
23The material → program table is in the executable (#2519), so the pair is chosen by what the shaders read, from
24`<work>/shaders/spirv/index.json` and the listings in `<work>/shaders/dxbc/disasm`:
25
26| | Vertex shader | Pixel shader |
27|---|---|---|
28| inputs | POSITION (xyz), NORMAL (xyz), TEXCOORD (xy) | SV_Position, TEXCOORD, COLOR |
29| user data | user SGPR 8 only (`ptr32_lo`) | user SGPR 8 (`ptr32_lo`) |
30| bindings | none | 0, 1, 2 (images, samplers, hash table) |
31| listing | three `s_load_dwordx4` from `s[8:9]` at 0x0, 0x40, 0x60; a 4-dword buffer load at 0x30 and a 16-dword one at 0x160 | one `s_load_dwordx8` from `s[8:9]` + 0x20; one `image_sample`; `exp mrt0` |
32
33On the 1.0.2.1 corpus 3 VS and 231 PS match the signatures, and 2 VS and 4 PS also match the listing patterns;
34they share one table layout. `tests/test_sandbox_pick.py` checks the picker on hand-written listings.
35
36## 3. The table the pair reads
37
38User SGPR 8 is a 32-bit pointer (the shaders force the high dword to 0) to one table in the heap:
39
40| Offset | Descriptor | Contents (byte offsets in the buffer) |
41|---|---|---|
42| 0x00 | V# | world rows 0–2 at 0x00, 0x10, 0x20 (xyz each), translation at 0x30; world = x·row0 + y·row1 + z·row2 + row3 |
43| 0x20 | T# | the albedo image (8 dwords) |
44| 0x40 | V# | light direction at 0xa0; view-projection at 0x160, clip = wx·r0 + wy·r1 + wz·r2 + r3 (D3D clip, y up, z 0..1) |
45| 0x60 | V# | colour at 0x00 (rgb × the lighting term, alpha as is) |
46
47`vk_sandbox` writes raw V#s (stride 0, NUM_RECORDS = the buffer's bytes, OOB_SELECT 3), registers each texture's
48T# words and the PS's S# literal in the descriptor hash table, builds the sampler from those S# words
49(`gfx10::decode`), and draws through a negative-height viewport so the D3D-convention matrices stay unchanged.
50
51## 4. Reproduce it
52
53```sh
54python -I tools/world_index.py ... --entities-out <work>/entities.jsonl # placements (docs/world.md)
55rpf9dump models "<package>/levels.rpf" <work>/assets
56rpf9dump ttpf "<package>/data/ttdb/maps/ttdb_maps_<n>_7.ttpf" <work>/ttpf_maps # n = 0..7
57rpf9dump ttpf "<package>/data/ttdb/terrain/ttdb_terrain_<n>_7.ttpf" <work>/ttpf_terrain # n = 0..7
58cmake --build runtime/build --target vk_sandbox
59python -I tools/sandbox.py --work <work> --entities <work>/entities.jsonl --models <work>/assets \
60 --textures <work>/ttpf_maps --textures <work>/ttpf_terrain [--center X Y] --window
61```
62
63Window keys: WASD move, right mouse button held to look, Q/E down/up (fly), Shift faster, 1 fly, 2 walk (eye 1.7 m
64over the highest scene triangle under the camera), 3 drive (eye 1.2 m, accelerates and steers), P screenshot,
65Esc quit. `--center` is in RAGE world metres; without it the densest 50 m cell of resolved props is used.
66
67## 5. Measured
68
69| | |
70|---|---|
71| map pools (8) | 133,697 textures exported, 0 failed, 7,030 skipped |
72| terrain pools (8) | 46,115 exported, 0 failed, 26,903 skipped (`rpf9dump`'s limits in [textures.md](textures.md)) |
73| test scene (one `levels.rpf` window) | 600 entities within 120 m, 150 placed (402 have no exported model in that window), 446 draws, 178 meshes, 345,782 triangles |
74| albedo | the material's DiffuseTex reference (`Param` = `joaat("DiffuseTex")` = `C8E8C282`): 422 of 446 draws textured with 93 textures from the map and terrain pools (69 with the map pools alone). Two-layer blend materials have no DiffuseTex: 11 references each, two albedos, two normal maps, packed maps and a blend mask; the first layer's albedo (`Param` `346394EA`, name unknown) brings it to 442 of 446 draws and 107 textures |
75| `--check` (640×360) | 114,503 pixels covered, 4,736 distinct colours (147 with the textures left out) |
76| window | about 90 frames per second with a `vkQueueWaitIdle` per frame; a 60-frame windowed run ends on the same pixels as the headless render |
77| walk / drive | eye at 1.70 m / 1.20 m over the roof the camera starts above |
78
79## 6. Limits and next
80
81* One pair, one forward pass. The world's own material shaders pull vertices (`SV_VertexID` only) and write the
82 G-buffer; drawing those needs their vertex fetch tables and the lighting passes that read the G-buffer.
83* The scene stores mip 0 box-scaled to 256 px (`--tex-size`), so the sampler's LOD range is clamped to 0.
84* Ground following uses the scene's own triangles; there is no collision against walls.
85* Draws are not culled or sorted, and every frame waits for the GPU; a large `--max-props` gets slow (each prop is
86 one draw per mesh: 150 props gave 446 draws).
diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt
index 8f1dce2ca..92101fc8f 100644
--- a/runtime/CMakeLists.txt
+++ b/runtime/CMakeLists.txt
@@ -818,7 +818,7 @@ endif()
818if(TARGET Vulkan::Headers) 818if(TARGET Vulkan::Headers)
819 foreach(tool vk_harness vk_texture_test vk_sampler_test vk_compute_test vk_store_test vk_pipeline_check vk_command_replay_test 819 foreach(tool vk_harness vk_texture_test vk_sampler_test vk_compute_test vk_store_test vk_pipeline_check vk_command_replay_test
820 vk_bindless_test vk_image_fuzz vk_descriptor_bench depth24_convert_test vk_predicate_capture_test vk_predicated_copy_test 820 vk_bindless_test vk_image_fuzz vk_descriptor_bench depth24_convert_test vk_predicate_capture_test vk_predicated_copy_test
821 vk_xdxr_build_test vk_queue_test) 821 vk_xdxr_build_test vk_queue_test vk_sandbox)
822 add_executable(${tool} test/${tool}.cpp) 822 add_executable(${tool} test/${tool}.cpp)
823 target_link_libraries(${tool} PRIVATE Vulkan::Headers ${CMAKE_DL_LIBS}) 823 target_link_libraries(${tool} PRIVATE Vulkan::Headers ${CMAKE_DL_LIBS})
824 if(WIN32) 824 if(WIN32)
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}
diff --git a/tests/test_sandbox_pick.py b/tests/test_sandbox_pick.py
new file mode 100644
index 000000000..2615bc0c7
--- /dev/null
+++ b/tests/test_sandbox_pick.py
@@ -0,0 +1,109 @@
1"""tools/sandbox.py: the shader pair is chosen by signature and descriptor layout, never by name."""
2import json
3import os
4import sys
5import tempfile
6import unittest
7
8sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "tools"))
9import sandbox # noqa: E402
10
11VS_TEXT = """\ts_load_dwordx4 s[0:3], s[8:9], null
12\ts_load_dwordx4 s[20:23], s[8:9], 0x40
13\ts_load_dwordx4 s[16:19], s[8:9], 0x60
14\ts_buffer_load_dwordx4 s[24:27], s[0:3], 0x30
15\ts_buffer_load_dwordx16 s[0:15], s[20:23], 0x160
16\texp pos0 v0, v1, v2, v3 done
17"""
18PS_TEXT = """\ts_load_dwordx8 s[4:11], s[8:9], 0x20
19\timage_sample v[0:3], v[2:3], s[4:11], s[0:3] dmask:0xf dim:SQ_RSRC_IMG_2D
20\texp mrt0 v0, v0, v1, v1 done compr vm
21"""
22
23
24def sig(*elems):
25 return [{"semantic": s, "semantic_index": 0, "mask": m} for s, m in elems]
26
27
28VS_SIG = sig(("POSITION", 7), ("NORMAL", 7), ("TEXCOORD", 3))
29PS_SIG = sig(("SV_Position", 15), ("TEXCOORD", 3), ("COLOR", 15))
30PTR8 = [{"kind": "ptr32_lo", "sgpr": 8}]
31
32
33class PickPair(unittest.TestCase):
34 def setUp(self):
35 self.tmp = tempfile.TemporaryDirectory()
36 self.root = self.tmp.name
37 os.makedirs(os.path.join(self.root, "spirv"))
38 os.makedirs(os.path.join(self.root, "dxbc", "disasm"))
39 self.index = {}
40
41 def tearDown(self):
42 self.tmp.cleanup()
43
44 def add(self, name, entry, text, spv=True):
45 self.index[name] = entry
46 with open(os.path.join(self.root, "dxbc", "disasm", name + ".s"), "w") as f:
47 f.write(text)
48 if spv:
49 open(os.path.join(self.root, "spirv", name + ".spv"), "wb").close()
50
51 def pick(self):
52 with open(os.path.join(self.root, "spirv", "index.json"), "w") as f:
53 json.dump(self.index, f)
54 return sandbox.pick_pair(self.root)
55
56 def names(self):
57 pair = self.pick()
58 return pair and tuple(os.path.splitext(os.path.basename(p))[0] for p in pair)
59
60 def test_picks_matching_pair(self):
61 self.add("a_vs", {"stage": "vs", "input_signature": VS_SIG, "user_sgpr_reads": PTR8, "bindings": []}, VS_TEXT)
62 self.add("b_ps", {"stage": "ps", "input_signature": PS_SIG, "user_sgpr_reads": PTR8 + [{"kind": "const32", "sgpr": 9}],
63 "bindings": [0, 1, 2]}, PS_TEXT)
64 self.assertEqual(self.names(), ("a_vs", "b_ps"))
65
66 def test_rejects_wrong_layout_and_signature(self):
67 self.add("a_vs", {"stage": "vs", "input_signature": VS_SIG, "user_sgpr_reads": PTR8, "bindings": []},
68 VS_TEXT.replace("0x160", "0x100"))
69 self.add("c_vs", {"stage": "vs", "input_signature": VS_SIG[:2], "user_sgpr_reads": PTR8, "bindings": []}, VS_TEXT)
70 self.add("b_ps", {"stage": "ps", "input_signature": PS_SIG, "user_sgpr_reads": PTR8, "bindings": [0, 1, 2]}, PS_TEXT)
71 self.assertIsNone(self.pick())
72
73 def test_rejects_two_samples_and_missing_spirv(self):
74 self.add("a_vs", {"stage": "vs", "input_signature": VS_SIG, "user_sgpr_reads": PTR8, "bindings": []}, VS_TEXT)
75 self.add("b_ps", {"stage": "ps", "input_signature": PS_SIG, "user_sgpr_reads": PTR8, "bindings": [0, 1, 2]},
76 PS_TEXT + PS_TEXT)
77 self.add("c_ps", {"stage": "ps", "input_signature": PS_SIG, "user_sgpr_reads": PTR8, "bindings": [0, 1, 2]},
78 PS_TEXT, spv=False)
79 self.assertIsNone(self.pick())
80 self.add("d_ps", {"stage": "ps", "input_signature": PS_SIG, "user_sgpr_reads": PTR8, "bindings": [0, 1, 2]}, PS_TEXT)
81 self.assertEqual(self.names(), ("a_vs", "d_ps"))
82
83 def test_missing_index(self):
84 self.assertIsNone(sandbox.pick_pair(os.path.join(self.root, "nowhere")))
85
86
87class CheckFrame(unittest.TestCase):
88 def frame(self, pixels, w, h):
89 fd, path = tempfile.mkstemp(suffix=".ppm")
90 with os.fdopen(fd, "wb") as f:
91 f.write(b"P6\n%d %d\n255\n" % (w, h) + bytes(c for p in pixels for c in p))
92 self.addCleanup(os.remove, path)
93 return path
94
95 def test_empty_frame_fails(self):
96 ok, msg = sandbox.check_frame(self.frame([(140, 173, 217)] * 100, 10, 10), False)
97 self.assertFalse(ok)
98 self.assertIn("0 of 100", msg)
99
100 def test_covered_frame(self):
101 px = [(140, 173, 217)] * 50 + [(64, 64, 64)] * 50
102 self.assertTrue(sandbox.check_frame(self.frame(px, 10, 10), False)[0])
103 self.assertFalse(sandbox.check_frame(self.frame(px, 10, 10), True)[0]) # textured needs colour variety
104 varied = [(140, 173, 217)] * 300 + [(i % 256, i // 256, 7) for i in range(300)]
105 self.assertTrue(sandbox.check_frame(self.frame(varied, 30, 20), True)[0])
106
107
108if __name__ == "__main__":
109 unittest.main()
diff --git a/tests/test_sandbox_scene.py b/tests/test_sandbox_scene.py
new file mode 100644
index 000000000..920c660e3
--- /dev/null
+++ b/tests/test_sandbox_scene.py
@@ -0,0 +1,97 @@
1"""tools/sandbox_scene.py: entity world rows, nearest-first selection and the packed vertex layout."""
2import os
3import sys
4import struct
5import unittest
6
7sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'tools'))
8import sandbox_scene
9
10class TestSandboxScene(unittest.TestCase):
11 def test_draw_rows(self):
12 result = sandbox_scene.draw_rows((0, 0, 0, 1), 1.0, 1.0, (10, 20, 30))
13 self.assertAlmostEqual(result[0][0], 1.0, places=6)
14 self.assertAlmostEqual(result[0][1], 0.0, places=6)
15 self.assertAlmostEqual(result[0][2], 0.0, places=6)
16 self.assertAlmostEqual(result[1][0], 0.0, places=6)
17 self.assertAlmostEqual(result[1][1], 1.0, places=6)
18 self.assertAlmostEqual(result[1][2], 0.0, places=6)
19 self.assertAlmostEqual(result[2][0], 0.0, places=6)
20 self.assertAlmostEqual(result[2][1], 0.0, places=6)
21 self.assertAlmostEqual(result[2][2], 1.0, places=6)
22 self.assertAlmostEqual(result[3][0], 10.0, places=6)
23 self.assertAlmostEqual(result[3][1], 20.0, places=6)
24 self.assertAlmostEqual(result[3][2], 30.0, places=6)
25
26 def test_draw_rows_rotation(self):
27 result = sandbox_scene.draw_rows((0, 0, -0.70710678, 0.70710678), 1, 1, (0, 0, 0))
28 self.assertAlmostEqual(result[0][0], 0.0, places=6)
29 self.assertAlmostEqual(result[0][1], 1.0, places=6)
30 self.assertAlmostEqual(result[0][2], 0.0, places=6)
31 self.assertAlmostEqual(result[1][0], -1.0, places=6)
32 self.assertAlmostEqual(result[1][1], 0.0, places=6)
33 self.assertAlmostEqual(result[1][2], 0.0, places=6)
34 self.assertAlmostEqual(result[2][0], 0.0, places=6)
35 self.assertAlmostEqual(result[2][1], 0.0, places=6)
36 self.assertAlmostEqual(result[2][2], 1.0, places=6)
37
38 def test_draw_rows_scale(self):
39 result = sandbox_scene.draw_rows((0, 0, 0, 1), 2.0, 3.0, (0, 0, 0))
40 self.assertAlmostEqual(result[0][0], 2.0, places=6)
41 self.assertAlmostEqual(result[0][1], 0.0, places=6)
42 self.assertAlmostEqual(result[0][2], 0.0, places=6)
43 self.assertAlmostEqual(result[1][0], 0.0, places=6)
44 self.assertAlmostEqual(result[1][1], 2.0, places=6)
45 self.assertAlmostEqual(result[1][2], 0.0, places=6)
46 self.assertAlmostEqual(result[2][0], 0.0, places=6)
47 self.assertAlmostEqual(result[2][1], 0.0, places=6)
48 self.assertAlmostEqual(result[2][2], 3.0, places=6)
49
50 def test_select_rows(self):
51 rows = [
52 {"_pos": [1, 1, 0]},
53 {"_pos": [5, 5, 0]},
54 {"_pos": [20, 20, 0]},
55 {"_pos": [3, 3, 0]}
56 ]
57 result = sandbox_scene.select_rows(rows, (0, 0), 10, 10)
58 self.assertEqual(len(result), 3)
59 self.assertAlmostEqual(result[0]["_pos"][0], 1.0, places=6)
60 self.assertAlmostEqual(result[0]["_pos"][1], 1.0, places=6)
61 self.assertAlmostEqual(result[1]["_pos"][0], 3.0, places=6)
62 self.assertAlmostEqual(result[1]["_pos"][1], 3.0, places=6)
63 self.assertAlmostEqual(result[2]["_pos"][0], 5.0, places=6)
64 self.assertAlmostEqual(result[2]["_pos"][1], 5.0, places=6)
65
66 result = sandbox_scene.select_rows(rows, (0, 0), 10, 2)
67 self.assertEqual(len(result), 2)
68 self.assertAlmostEqual(result[0]["_pos"][0], 1.0, places=6)
69 self.assertAlmostEqual(result[0]["_pos"][1], 1.0, places=6)
70 self.assertAlmostEqual(result[1]["_pos"][0], 3.0, places=6)
71 self.assertAlmostEqual(result[1]["_pos"][1], 3.0, places=6)
72
73 def test_mesh_bytes(self):
74 prim = {
75 "positions": [(0, 0, 0), (1, 0, 0), (0, 1, 0)],
76 "normals": [(0, 0, 1)] * 3,
77 "uvs": [(0, 0), (1, 0), (0, 1)],
78 "indices": [0, 1, 2]
79 }
80 b = sandbox_scene.mesh_bytes(prim)
81 self.assertEqual(len(b), 116)
82 self.assertEqual(tuple(struct.unpack_from('<II', b, 0)), (3, 3))
83 self.assertEqual(tuple(struct.unpack_from('<8f', b, 40)), (1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 0.0))
84 self.assertEqual(tuple(struct.unpack_from('<3I', b, 104)), (0, 1, 2))
85
86 def test_mesh_bytes_no_normals(self):
87 prim = {
88 "positions": [(0, 0, 0), (1, 0, 0), (0, 1, 0)],
89 "normals": [],
90 "indices": [0, 1, 2]
91 }
92 b = sandbox_scene.mesh_bytes(prim)
93 self.assertEqual(tuple(struct.unpack_from('<8f', b, 8)), (0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0))
94 self.assertEqual(tuple(struct.unpack_from('<8f', b, 40)), (1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0))
95
96if __name__ == "__main__":
97 unittest.main()
diff --git a/tools/sandbox.py b/tools/sandbox.py
new file mode 100644
index 000000000..3fa4bf707
--- /dev/null
+++ b/tools/sandbox.py
@@ -0,0 +1,169 @@
1#!/usr/bin/env python3
2"""Real-shader sandbox: walk, fly or drive through placed props drawn by the game's own translated shaders.
3
4 python -I tools/sandbox.py --work <work> --entities <entities.jsonl> --models <assets> --textures <ttpf out> \
5 [--center X Y] [--radius M] [--max-props N] (--window | --check)
6
7It packs the props around --center with tools/sandbox_scene.py, picks a translated VS/PS pair from
8<work>/shaders/spirv/index.json and runs runtime/build/vk_sandbox. The pair is chosen by what the shaders read,
9not by name (the material -> program table is in the executable, #2519): a vertex shader with POSITION, NORMAL
10and TEXCOORD inputs, user SGPR 8 as its only user data and no bindings, whose listing loads three descriptors from
11s[8:9] at 0x0/0x40/0x60, a world translation at 0x30 and a 4x4 at 0x160; and a pixel shader with TEXCOORD and
12COLOR inputs that loads one T# from s[8:9] + 0x20 and samples it once. vk_sandbox fills that table (see its
13header). --check renders one frame headless and prints only counts: exit 0 when the frame is covered and, with
14textures, shows texture detail; 77 when the package, the pair or a GPU is missing. Standard library only.
15"""
16import argparse
17import json
18import os
19import re
20import subprocess
21import sys
22import tempfile
23
24HERE = os.path.dirname(os.path.abspath(__file__))
25sys.path.insert(0, HERE)
26import sandbox_scene # noqa: E402
27
28VS_LAYOUT = (r"s_load_dwordx4 s\[\d+:\d+\], s\[8:9\], (?:null|0)\b", r"s_load_dwordx4 s\[\d+:\d+\], s\[8:9\], 0x40\b",
29 r"s_load_dwordx4 s\[\d+:\d+\], s\[8:9\], 0x60\b", r"s_buffer_load_dwordx16 s\[\d+:\d+\], s\[\d+:\d+\], 0x160\b",
30 r"s_buffer_load_dwordx4 s\[\d+:\d+\], s\[\d+:\d+\], 0x30\b")
31SKY = bytes((140, 173, 217)) # vk_sandbox's clear colour (0.55, 0.68, 0.85) in 8 bits
32PS_LAYOUT = (r"s_load_dwordx8 s\[\d+:\d+\], s\[8:9\], 0x20\b", r"\bimage_sample\b", r"\bexp mrt0\b")
33
34
35def _signature(entry):
36 return [(e.get("semantic"), e.get("semantic_index"), e.get("mask")) for e in entry.get("input_signature") or []]
37
38
39def _listing_matches(disasm_dir, name, patterns):
40 try:
41 with open(os.path.join(disasm_dir, name + ".s"), encoding="utf-8", errors="replace") as f:
42 text = f.read()
43 except OSError:
44 return False
45 return text.count("image_sample") <= 1 and all(re.search(p, text) for p in patterns)
46
47
48def pick_pair(shaders_dir):
49 """(vs.spv, ps.spv) paths of the first matching pair in name order, or None."""
50 spirv = os.path.join(shaders_dir, "spirv")
51 disasm = os.path.join(shaders_dir, "dxbc", "disasm")
52 try:
53 with open(os.path.join(spirv, "index.json"), encoding="utf-8") as f:
54 index = json.load(f)
55 except (OSError, ValueError):
56 return None
57 ptr8 = {"kind": "ptr32_lo", "sgpr": 8}
58 vs = ps = None
59 for name in sorted(index):
60 e = index[name]
61 if not os.path.isfile(os.path.join(spirv, name + ".spv")):
62 continue
63 if (vs is None and e.get("stage") == "vs" and not e.get("bindings")
64 and e.get("user_sgpr_reads") == [ptr8]
65 and _signature(e) == [("POSITION", 0, 7), ("NORMAL", 0, 7), ("TEXCOORD", 0, 3)]
66 and _listing_matches(disasm, name, VS_LAYOUT)):
67 vs = name
68 elif (ps is None and e.get("stage") == "ps" and e.get("bindings") == [0, 1, 2]
69 and ptr8 in (e.get("user_sgpr_reads") or [])
70 and [s[0] for s in _signature(e)] == ["SV_Position", "TEXCOORD", "COLOR"]
71 and _listing_matches(disasm, name, PS_LAYOUT)):
72 ps = name
73 if vs and ps:
74 return os.path.join(spirv, vs + ".spv"), os.path.join(spirv, ps + ".spv")
75 return None
76
77
78def find_tool(build):
79 for name in ("vk_sandbox.exe", "vk_sandbox"):
80 path = os.path.join(build, name)
81 if os.path.isfile(path):
82 return path
83 return None
84
85
86def read_ppm(path):
87 with open(path, "rb") as f:
88 data = f.read()
89 head = data.split(b"\n", 3)
90 w, h = (int(v) for v in head[1].split())
91 return w, h, head[3]
92
93
94def check_frame(path, textured):
95 """(ok, message) from the rendered frame: coverage and, with textures, colour variety."""
96 w, h, px = read_ppm(path)
97 sky = SKY
98 covered, colours = 0, set()
99 for i in range(0, len(px), 3):
100 p = px[i:i + 3]
101 if abs(p[0] - sky[0]) > 1 or abs(p[1] - sky[1]) > 1 or abs(p[2] - sky[2]) > 1:
102 covered += 1
103 colours.add(p)
104 ok = covered >= w * h // 100 and (not textured or len(colours) >= 256)
105 return ok, f"{covered} of {w * h} pixels covered, {len(colours)} distinct colours"
106
107
108def main(argv=None):
109 ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
110 ap.add_argument("--work", required=True, help="make_game.py work folder (holds shaders/spirv and shaders/dxbc)")
111 ap.add_argument("--entities", required=True)
112 ap.add_argument("--models", required=True)
113 ap.add_argument("--textures", action="append", default=[])
114 ap.add_argument("--center", type=float, nargs=2, metavar=("X", "Y"))
115 ap.add_argument("--radius", type=float, default=150.0)
116 ap.add_argument("--max-props", type=int, default=400)
117 ap.add_argument("--build", default=os.path.join(HERE, "..", "runtime", "build"))
118 ap.add_argument("--scene", help="scene file to write (default: a temporary file)")
119 mode = ap.add_mutually_exclusive_group(required=True)
120 mode.add_argument("--window", action="store_true")
121 mode.add_argument("--check", action="store_true")
122 a = ap.parse_args(argv)
123
124 tool = find_tool(a.build)
125 pair = pick_pair(os.path.join(a.work, "shaders"))
126 if not tool or not pair or not os.path.isfile(a.entities):
127 print("unsupported: " + ("vk_sandbox is not built" if not tool else
128 "no matching translated shader pair" if not pair else "no entities file"))
129 return 77
130 tmp = frame = None
131 scene = a.scene
132 if not scene:
133 fd, scene = tempfile.mkstemp(suffix=".bin")
134 os.close(fd)
135 tmp = scene
136 try:
137 try:
138 stats = sandbox_scene.build(argparse.Namespace(entities=a.entities, models=a.models, textures=a.textures,
139 center=a.center, radius=a.radius, max_props=a.max_props,
140 tex_size=256, out=scene))
141 except SystemExit as e: # build() exits when no entity resolves to an exported model
142 print(f"unsupported: {e}")
143 return 77
144 print(f"scene: {stats['placed']} props, {stats['draws']} draws, {stats['textures']} textures, "
145 f"{stats['textured_draws']} textured draws")
146 if stats["draws"] == 0:
147 print("unsupported: no prop near the centre resolves to an exported model")
148 return 77
149 x, y, z = stats["center"]
150 cam = [str(x - 40), str(y - 40), str(z + 25), "45", "-20"]
151 if a.window:
152 return subprocess.call([tool, scene, *pair, "--window", "--cam", *cam])
153 frame = scene + ".ppm"
154 r = subprocess.run([tool, scene, *pair, "--out", frame, "--size", "640", "360", "--cam", *cam],
155 capture_output=True, text=True)
156 if r.returncode:
157 print((r.stdout + r.stderr).strip().splitlines()[-1] if (r.stdout + r.stderr).strip() else "vk_sandbox failed")
158 return r.returncode
159 ok, msg = check_frame(frame, stats["textured_draws"] > 0)
160 print(("PASS: " if ok else "FAIL: ") + msg)
161 return 0 if ok else 1
162 finally:
163 for path in (tmp, frame):
164 if path and os.path.exists(path):
165 os.remove(path)
166
167
168if __name__ == "__main__":
169 sys.exit(main())
diff --git a/tools/sandbox_scene.py b/tools/sandbox_scene.py
new file mode 100644
index 000000000..ac5555251
--- /dev/null
+++ b/tools/sandbox_scene.py
@@ -0,0 +1,176 @@
1#!/usr/bin/env python3
2"""Pack the placed props around one spot into a scene file for runtime/test/vk_sandbox.
3
4Reads the same inputs as ``world_build.py --placements`` (``world_index.py --entities-out`` rows, the
5``rpf9dump models`` manifests and the ``rpf9dump ttpf`` texture manifests), keeps the entities within
6--radius metres of --center (RAGE world x y, Z-up), and writes one little-endian file:
7
8 "LSB1", u32 version 1, u32 textures, u32 meshes, u32 draws, f32 center[3]
9 textures: u32 w, u32 h, w*h RGBA8 (the material's DiffuseTex, mip 0 box-scaled to --tex-size)
10 meshes: u32 vertex count, u32 index count, vertices (f32 pos[3], f32 normal[3], f32 uv[2]), u32 indices
11 draws: u32 mesh, i32 texture (-1: none), f32 rows[4][3]
12
13Positions stay in model space; a draw's rows are the entity's world transform as three basis rows plus the
14translation, world = x*row0 + y*row1 + z*row2 + row3 (RAGE Z-up). The file holds decoded game data, so it
15stays in the user's work folder. Standard library only.
16"""
17import argparse
18import math
19import os
20import struct
21import sys
22
23sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
24import dds_png # noqa: E402
25import glb_writer # noqa: E402
26import world_build # noqa: E402
27
28DIFFUSE_TEX = "C8E8C282" # joaat("DiffuseTex"), the albedo Param of a material texture reference
29# Two-layer blend materials have no DiffuseTex; their first layer's albedo sits in this slot (name not known yet;
30# beside it are the second layer's albedo, two normal maps, packed material maps and the blend mask).
31LAYER0_ALBEDO = "346394EA"
32
33
34def select_rows(rows, center, radius, limit):
35 """Rows within radius of center (x, y), nearest first, at most limit."""
36 cx, cy = center
37 near = []
38 for row in rows:
39 dx, dy = row["_pos"][0] - cx, row["_pos"][1] - cy
40 d = math.hypot(dx, dy)
41 if d <= radius:
42 near.append((d, row))
43 near.sort(key=lambda t: t[0])
44 return [row for _, row in near[:limit]]
45
46
47def draw_rows(rotation, scale_xy, scale_z, position):
48 """The VS's world rows (basis vectors then translation) for one entity."""
49 m, _, _ = world_build.entity_transform(rotation, scale_xy, scale_z)
50 rows = [[m[i][j] for i in range(3)] for j in range(3)] # column j of M is the image of model axis j
51 rows.append([float(v) for v in position])
52 return rows
53
54
55def mesh_bytes(prim):
56 pos, nrm, uvs, idx = prim["positions"], prim.get("normals") or [], prim.get("uvs") or [], prim["indices"]
57 out = bytearray(struct.pack("<II", len(pos), len(idx)))
58 for i, p in enumerate(pos):
59 n = nrm[i] if i < len(nrm) else (0.0, 0.0, 1.0)
60 uv = uvs[i] if i < len(uvs) else (0.0, 0.0)
61 out += struct.pack("<8f", p[0], p[1], p[2], n[0], n[1], n[2], uv[0], uv[1])
62 out += struct.pack(f"<{len(idx)}I", *idx)
63 return bytes(out)
64
65
66def texture_bytes(dds_path, max_size):
67 try:
68 with open(dds_path, "rb") as f:
69 w, h, rgba = dds_png.decode_dds(f.read())
70 w, h, rgba = dds_png.downscale_rgba(w, h, rgba, max_size)
71 except (dds_png.DdsError, OSError, ValueError):
72 return None
73 return struct.pack("<II", w, h) + bytes(rgba)
74
75
76def build(args):
77 rows, counts = world_build.load_placements(args.entities)
78 entries = []
79 for path in world_build.discover_model_manifests(args.models):
80 data = world_build._load_json_dict(path) or {}
81 entries += [(os.path.dirname(path), it) for it in data.get("Items") or [] if isinstance(it, dict)]
82 index = world_build.model_name_index(entries, world_build._get_world_names())
83 ttpf = {}
84 for root in args.textures:
85 for k, v in world_build.index_ttpf_textures(root).items():
86 ttpf.setdefault(k, v)
87 if args.center is None: # the 50 m cell holding the most entities that resolve to a model
88 cells = {}
89 for row in rows:
90 if row["_arch"] in index:
91 key = (math.floor(row["_pos"][0] / 50), math.floor(row["_pos"][1] / 50))
92 cells[key] = cells.get(key, 0) + 1
93 if not cells:
94 raise SystemExit("no entity resolves to an exported model")
95 best = max(cells, key=cells.get)
96 args.center = [(best[0] + 0.5) * 50, (best[1] + 0.5) * 50]
97 picked = select_rows(rows, args.center, args.radius, args.max_props * 4)
98
99 textures, tex_ids = [], {}
100 meshes, mesh_ids = [], {}
101 draws = []
102 stats = {"entities": len(picked), "placed": 0, "unresolved": 0, "textured_draws": 0, "z": []}
103 for row in picked:
104 model, _ = world_build.resolve_placement(index, row["_arch"], row.get("key"))
105 if model is None:
106 stats["unresolved"] += 1
107 continue
108 models_dir, item = model
109 obj = os.path.join(models_dir, item.get("File") or "")
110 key = (os.path.normcase(obj), id(item)) # archetypes sharing an OBJ can differ in materials
111 if key not in mesh_ids:
112 try:
113 prims = glb_writer.parse_obj(obj, is_path=True, up_axis="y")
114 except (OSError, glb_writer.GlbError, ValueError):
115 prims = []
116 tex_map = world_build.resolve_model_textures(models_dir, item, ttpf, LAYER0_ALBEDO)
117 tex_map.update(world_build.resolve_model_textures(models_dir, item, ttpf, DIFFUSE_TEX))
118 shaders = world_build._list_field(item, "MeshShaders")
119 ids = []
120 for p in prims:
121 if not p.get("positions") or not p.get("indices"):
122 continue
123 g = p.get("group_index", 0)
124 sidx = shaders[g] if 0 <= g < len(shaders) else g
125 tex = -1
126 dds = tex_map.get(sidx)
127 if dds:
128 dkey = os.path.normcase(dds)
129 if dkey not in tex_ids:
130 blob = texture_bytes(dds, args.tex_size)
131 tex_ids[dkey] = len(textures) if blob else -1
132 if blob:
133 textures.append(blob)
134 tex = tex_ids[dkey]
135 ids.append((len(meshes), tex))
136 meshes.append(mesh_bytes(p))
137 mesh_ids[key] = ids
138 if not mesh_ids[key]:
139 stats["unresolved"] += 1
140 continue
141 rws = draw_rows(row["_rot"], row["_sxy"], row["_sz"], row["_pos"])
142 for mesh, tex in mesh_ids[key]:
143 draws.append(struct.pack("<Ii12f", mesh, tex, *[v for r in rws for v in r]))
144 stats["textured_draws"] += tex >= 0
145 stats["placed"] += 1
146 stats["z"].append(row["_pos"][2])
147 if stats["placed"] >= args.max_props:
148 break
149 z = sorted(stats.pop("z")) or [0.0]
150 center = [args.center[0], args.center[1], z[len(z) // 2]]
151 with open(args.out, "wb") as f:
152 f.write(b"LSB1" + struct.pack("<4I3f", 1, len(textures), len(meshes), len(draws), *center))
153 for blob in textures + meshes + draws:
154 f.write(blob)
155 stats.update(textures=len(textures), meshes=len(meshes), draws=len(draws), center=center,
156 selected_rows=counts["selected"])
157 return stats
158
159
160def main(argv=None):
161 ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
162 ap.add_argument("--entities", required=True, help="world_index.py --entities-out file (JSON lines)")
163 ap.add_argument("--models", required=True, help="folder holding rpf9dump models manifests")
164 ap.add_argument("--textures", action="append", default=[], help="folder holding rpf9dump ttpf manifests (repeatable)")
165 ap.add_argument("--center", type=float, nargs=2, metavar=("X", "Y"), help="RAGE world x y (default: densest 50 m cell)")
166 ap.add_argument("--radius", type=float, default=150.0)
167 ap.add_argument("--max-props", type=int, default=400, help="entities to place, nearest first (each can be several draws)")
168 ap.add_argument("--tex-size", type=int, default=256)
169 ap.add_argument("--out", required=True)
170 stats = build(ap.parse_args(argv))
171 print(" ".join(f"{k}={v}" for k, v in stats.items()))
172 return 0
173
174
175if __name__ == "__main__":
176 sys.exit(main())