Debian Codegraph @

Sources/nCine/Graphics/RHI/Software/tests/SwBackendHarness.cpp

raw
1 // Standalone harness for the integrated software RHI backend.
2 //
3 // It drives the `RHI::Software::Sw*` types through the `nCine::RHI::` contract aliases exactly the way
4 // `RenderCommand::Issue()` drives them for a sprite: it builds a render-target framebuffer, a DefaultSprite
5 // program fed the offline reflection, a checker/solid texture, vertex/index buffers and a vertex array,
6 // fills the InstanceBlock (ortho projection, identity view, a placing model matrix, color, texRect,
7 // spriteSize), then `Use()`s the program, binds, commits and issues `Device::DrawArrays`/`DrawElements`.
8 // Finally it asserts known pixels and writes the framebuffer to a PNG.
9 //
10 // Build (from the scratchpad, MSVC): see the cl.exe command in the accompanying run; the backend needs
11 // only RhiTypes.h, Primitives and ShaderCompilerTypes.h besides its own sources.
12
13 // WITH_RHI_SOFTWARE is defined on the compiler command line so every translation unit sees it
14
15 #include "nCine/Graphics/RHI/Software/SwBackend.h"
16 #include "nCine/Graphics/RHI/Software/SwRaster.h"
17 #include "Shaders/Generated/DefaultSprite.h"
18 #include "Shaders/Generated/TexturedBackground.h"
19 #include "Shaders/Generated/TexturedBackgroundCircle.h"
20 #include "Shaders/Generated/Combine.h"
21 #include "Shaders/Generated/PaletteRemap.h"
22
23 #include <algorithm>
24 #include <cmath>
25 #include <cstdint>
26 #include <cstdio>
27 #include <cstring>
28 #include <fstream>
29 #include <vector>
30
31 using namespace nCine;
32
33 namespace
34 {
35 // ---- Minimal RGBA8 PNG writer (stored/uncompressed DEFLATE, so no zlib dependency) ----
36
37 void PutBE32(std::vector<std::uint8_t>& out, std::uint32_t v)
38 {
39 out.push_back(std::uint8_t(v >> 24));
40 out.push_back(std::uint8_t(v >> 16));
41 out.push_back(std::uint8_t(v >> 8));
42 out.push_back(std::uint8_t(v));
43 }
44
45 std::uint32_t Crc32(const std::uint8_t* data, std::size_t length)
46 {
47 std::uint32_t crc = 0xFFFFFFFFu;
48 for (std::size_t i = 0; i < length; i++) {
49 crc ^= data[i];
50 for (int b = 0; b < 8; b++) {
51 crc = (crc >> 1) ^ (0xEDB88320u & (~(crc & 1u) + 1u));
52 }
53 }
54 return crc ^ 0xFFFFFFFFu;
55 }
56
57 std::uint32_t Adler32(const std::uint8_t* data, std::size_t length)
58 {
59 std::uint32_t a = 1, b = 0;
60 for (std::size_t i = 0; i < length; i++) {
61 a = (a + data[i]) % 65521u;
62 b = (b + a) % 65521u;
63 }
64 return (b << 16) | a;
65 }
66
67 void WriteChunk(std::vector<std::uint8_t>& png, const char* type, const std::vector<std::uint8_t>& data)
68 {
69 PutBE32(png, std::uint32_t(data.size()));
70 std::vector<std::uint8_t> typeAndData;
71 typeAndData.insert(typeAndData.end(), type, type + 4);
72 typeAndData.insert(typeAndData.end(), data.begin(), data.end());
73 png.insert(png.end(), typeAndData.begin(), typeAndData.end());
74 PutBE32(png, Crc32(typeAndData.data(), typeAndData.size()));
75 }
76
77 bool WritePng(const char* path, const std::uint8_t* rgba, std::int32_t width, std::int32_t height, std::int32_t stride)
78 {
79 // Filtered raw data: one filter byte (0 = none) per scanline followed by the RGBA row
80 std::vector<std::uint8_t> raw;
81 raw.reserve(std::size_t(height) * (1 + std::size_t(width) * 4));
82 for (std::int32_t y = 0; y < height; y++) {
83 raw.push_back(0);
84 const std::uint8_t* row = rgba + std::size_t(y) * stride;
85 raw.insert(raw.end(), row, row + std::size_t(width) * 4);
86 }
87
88 // zlib stream wrapping stored DEFLATE blocks
89 std::vector<std::uint8_t> zlib;
90 zlib.push_back(0x78);
91 zlib.push_back(0x01);
92 std::size_t offset = 0;
93 while (offset < raw.size()) {
94 std::size_t blockLen = raw.size() - offset;
95 if (blockLen > 65535) {
96 blockLen = 65535;
97 }
98 const bool last = (offset + blockLen >= raw.size());
99 zlib.push_back(last ? 1 : 0);
100 zlib.push_back(std::uint8_t(blockLen & 0xFF));
101 zlib.push_back(std::uint8_t((blockLen >> 8) & 0xFF));
102 const std::uint16_t nlen = std::uint16_t(~std::uint16_t(blockLen));
103 zlib.push_back(std::uint8_t(nlen & 0xFF));
104 zlib.push_back(std::uint8_t((nlen >> 8) & 0xFF));
105 zlib.insert(zlib.end(), raw.begin() + offset, raw.begin() + offset + blockLen);
106 offset += blockLen;
107 }
108 const std::uint32_t adler = Adler32(raw.data(), raw.size());
109 PutBE32(zlib, adler);
110
111 std::vector<std::uint8_t> png = {0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A};
112 std::vector<std::uint8_t> ihdr;
113 PutBE32(ihdr, std::uint32_t(width));
114 PutBE32(ihdr, std::uint32_t(height));
115 ihdr.push_back(8); // bit depth
116 ihdr.push_back(6); // color type: RGBA
117 ihdr.push_back(0); // compression
118 ihdr.push_back(0); // filter
119 ihdr.push_back(0); // interlace
120 WriteChunk(png, "IHDR", ihdr);
121 WriteChunk(png, "IDAT", zlib);
122 WriteChunk(png, "IEND", std::vector<std::uint8_t>{});
123
124 std::ofstream file(path, std::ios::binary);
125 if (!file) {
126 return false;
127 }
128 file.write(reinterpret_cast<const char*>(png.data()), std::streamsize(png.size()));
129 return file.good();
130 }
131
132 // ---- Pixel assertions ----
133
134 int g_checks = 0;
135 int g_failures = 0;
136
137 void MakeTranslation(float tx, float ty, float* m)
138 {
139 for (int i = 0; i < 16; i++) {
140 m[i] = 0.0f;
141 }
142 m[0] = m[5] = m[10] = m[15] = 1.0f;
143 m[12] = tx;
144 m[13] = ty;
145 }
146
147 const std::uint8_t* PixelAt(const std::uint8_t* pixels, std::int32_t stride, std::int32_t x, std::int32_t y)
148 {
149 return pixels + std::size_t(y) * stride + std::size_t(x) * 4;
150 }
151
152 void CheckPixel(const std::uint8_t* pixels, std::int32_t stride, std::int32_t x, std::int32_t y,
153 int r, int g, int b, int a, int tolerance, const char* label)
154 {
155 g_checks++;
156 const std::uint8_t* p = PixelAt(pixels, stride, x, y);
157 const bool ok = std::abs(int(p[0]) - r) <= tolerance && std::abs(int(p[1]) - g) <= tolerance &&
158 std::abs(int(p[2]) - b) <= tolerance && std::abs(int(p[3]) - a) <= tolerance;
159 if (!ok) {
160 g_failures++;
161 std::printf(" FAIL %-28s (%3d,%3d) = (%3d,%3d,%3d,%3d), expected (%3d,%3d,%3d,%3d)\n",
162 label, x, y, p[0], p[1], p[2], p[3], r, g, b, a);
163 } else {
164 std::printf(" ok %-28s (%3d,%3d) = (%3d,%3d,%3d,%3d)\n", label, x, y, p[0], p[1], p[2], p[3]);
165 }
166 }
167
168 // ---- Uniform-buffer suballocator (registered with the backend, backed by one host buffer) ----
169
170 RHI::Buffer* g_uniformBuffer = nullptr;
171 std::uint32_t g_uniformBump = 0;
172
173 RHI::BufferRange AllocUniformRange(std::uint32_t bytes)
174 {
175 RHI::BufferRange range;
176 const std::uint32_t alignedOffset = (g_uniformBump + 15u) & ~15u;
177 range.object = g_uniformBuffer;
178 range.offset = alignedOffset;
179 range.size = bytes;
180 range.mapBase = g_uniformBuffer->HostData();
181 g_uniformBump = alignedOffset + bytes;
182 return range;
183 }
184
185 // ---- One sprite draw, replaying CommitAll() + Issue() ----
186
187 enum class DrawKind { Arrays, Elements };
188
189 void DrawSprite(RHI::ShaderProgram& program, RHI::ShaderUniforms& camera, RHI::ShaderUniformBlocks& blocks,
190 RHI::Texture& texture, RHI::Buffer& vbo, RHI::Buffer& ibo,
191 const float* model, const float* color, const float* texRect, const float* spriteSize,
192 bool blend, BlendingFactor srcFactor, BlendingFactor dstFactor, const Recti* scissor, DrawKind kind)
193 {
194 // Fill the InstanceBlock members (the equivalent of the node transform + material uniforms)
195 auto* instanceBlock = blocks.GetUniformBlock("InstanceBlock");
196 instanceBlock->GetUniform("modelMatrix")->SetFloatVector(model);
197 instanceBlock->GetUniform("color")->SetFloatVector(color);
198 instanceBlock->GetUniform("texRect")->SetFloatVector(texRect);
199 instanceBlock->GetUniform("spriteSize")->SetFloatVector(spriteSize);
200
201 // CommitAll(): copy the block into the streaming uniform buffer
202 blocks.CommitUniformBlocks();
203
204 // Issue(): material.Bind() -> textures, program, uniform blocks
205 texture.Bind(0);
206 program.Use();
207 blocks.Bind();
208 // material.CommitUniforms() -> loose (camera) uniforms
209 camera.CommitUniforms();
210
211 // Blend + scissor state, as RenderCommand::Issue() sets around the draw
212 RHI::Device::SetBlendingEnabled(blend);
213 if (blend) {
214 RHI::Device::SetBlendingFactors(srcFactor, dstFactor, BlendingFactor::One, dstFactor);
215 }
216 RHI::Device::ScissorState savedScissor = RHI::Device::GetScissorState();
217 if (scissor != nullptr) {
218 RHI::Device::SetScissor(*scissor);
219 } else {
220 RHI::Device::SetScissorTestEnabled(false);
221 }
222
223 // material.DefineVertexFormat() + geometry.Bind() + geometry.Draw()
224 program.DefineVertexFormat(&vbo, &ibo, 0);
225 vbo.Bind();
226 if (kind == DrawKind::Arrays) {
227 RHI::Device::DrawArrays(PrimitiveType::TriangleStrip, 0, 4);
228 } else {
229 ibo.Bind();
230 RHI::Device::DrawElements(PrimitiveType::Triangles, 6, 0, 0);
231 }
232
233 RHI::Device::SetScissorState(savedScissor);
234 }
235 }
236
237 // ---- Shared helpers for the effect tests ----
238
239 void MakePath(const char* baseDir, const char* name, char* out, std::size_t outSize)
240 {
241 std::snprintf(out, outSize, "%s/%s", baseDir, name);
242 }
243
244 // Ortho projection with a top-left origin, mapping model [0,W]x[0,H] to the viewport (y flipped)
245 void BuildOrtho(std::int32_t width, std::int32_t height, float* m)
246 {
247 const float near = -1.0f, far = 1.0f;
248 const float proj[16] = {
249 2.0f / width, 0.0f, 0.0f, 0.0f,
250 0.0f, -2.0f / height, 0.0f, 0.0f,
251 0.0f, 0.0f, -2.0f / (far - near), 0.0f,
252 -1.0f, 1.0f, -(far + near) / (far - near), 1.0f
253 };
254 std::memcpy(m, proj, sizeof(proj));
255 }
256
257 // Writes one instance's std140 InstanceBlock bytes (112-byte layout shared by every sprite-family shader)
258 void FillInstanceRaw(std::uint8_t* dst, const float* model, const float* color, const float* texRect,
259 const float* spriteSize, float palOffset)
260 {
261 std::memset(dst, 0, 112);
262 std::memcpy(dst + 0, model, 16 * sizeof(float));
263 std::memcpy(dst + 64, color, 4 * sizeof(float));
264 std::memcpy(dst + 80, texRect, 4 * sizeof(float));
265 std::memcpy(dst + 96, spriteSize, 2 * sizeof(float));
266 std::memcpy(dst + 104, &palOffset, sizeof(float));
267 }
268
269 const float kIdentityView[16] = {1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1};
270 const float kTexRectFull[4] = {1.0f, 0.0f, 1.0f, 0.0f};
271 const float kWhite[4] = {1.0f, 1.0f, 1.0f, 1.0f};
272
273 bool RunSpriteTest(const char* baseDir)
274 {
275 char outputPath[512];
276 MakePath(baseDir, "sw_sprite.png", outputPath, sizeof(outputPath));
277 constexpr std::int32_t Width = 256;
278 constexpr std::int32_t Height = 256;
279 g_uniformBump = 0;
280
281 std::printf("\n=== DefaultSprite (regression) ===\n");
282
283 // --- Program from the offline DefaultSprite reflection ---
284 RHI::ShaderProgram program(RHI::ShaderProgram::QueryPhase::Immediate);
285 program.SetReflection(&nCine::ShadersGen::DefaultSprite.Variants[0]);
286 program.Link(RHI::ShaderProgram::Introspection::Enabled);
287 program.SetObjectLabel("DefaultSprite");
288
289 // --- Streaming uniform buffer + suballocator ---
290 RHI::Buffer uniformBuffer(BufferTarget::Uniform);
291 uniformBuffer.BufferData(64 * 1024, nullptr, BufferUsage::StreamDraw);
292 g_uniformBuffer = &uniformBuffer;
293 RHI::ShaderUniformBlocks::SetUniformRangeAllocator(&AllocUniformRange);
294
295 // --- Camera (loose) uniforms: an ortho projection (top-left origin) and an identity view ---
296 std::vector<std::uint8_t> cameraBuffer(program.GetUniformsSize() + 16, 0);
297 RHI::ShaderUniforms camera(&program);
298 camera.SetUniformsDataPointer(cameraBuffer.data());
299
300 const float near = -1.0f, far = 1.0f;
301 const float projection[16] = {
302 2.0f / Width, 0.0f, 0.0f, 0.0f,
303 0.0f, -2.0f / Height, 0.0f, 0.0f,
304 0.0f, 0.0f, -2.0f / (far - near), 0.0f,
305 -1.0f, 1.0f, -(far + near) / (far - near), 1.0f
306 };
307 const float view[16] = {
308 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1
309 };
310 camera.GetUniform("uProjectionMatrix")->SetFloatVector(projection);
311 camera.GetUniform("uViewMatrix")->SetFloatVector(view);
312
313 // --- Instance block storage ---
314 std::vector<std::uint8_t> blockBuffer(program.GetUniformBlocksSize() + 16, 0);
315 RHI::ShaderUniformBlocks blocks(&program);
316 blocks.SetUniformsDataPointer(blockBuffer.data());
317
318 // --- Textures ---
319 // 2x2 checker (RGBA): top-left red, top-right green, bottom-left blue, bottom-right yellow
320 const std::uint8_t checker[16] = {
321 255, 0, 0, 255, 0, 255, 0, 255,
322 0, 0, 255, 255, 255, 255, 0, 255
323 };
324 RHI::Texture checkerTexture(TextureTarget::Texture2D);
325 checkerTexture.TexImage2D(0, PixelFormat::RGBA8, false, 2, 2, checker);
326
327 // 1x1 solid white (for color-modulation and blend tests)
328 const std::uint8_t white[4] = {255, 255, 255, 255};
329 RHI::Texture whiteTexture(TextureTarget::Texture2D);
330 whiteTexture.TexImage2D(0, PixelFormat::RGBA8, false, 1, 1, white);
331
332 // --- Vertex/index buffers + vertex array (mirroring the sprite draw protocol) ---
333 RHI::Buffer vbo(BufferTarget::Vertex);
334 vbo.BufferData(4 * 4 * sizeof(float), nullptr, BufferUsage::StaticDraw);
335 RHI::Buffer ibo(BufferTarget::Index);
336 const std::uint16_t indices[6] = {0, 1, 2, 2, 1, 3};
337 ibo.BufferData(sizeof(indices), indices, BufferUsage::StaticDraw);
338 RHI::VertexArray vao;
339 vao.SetObjectLabel("SpriteQuad");
340
341 // --- Render target ---
342 RHI::Texture colorTexture(TextureTarget::Texture2D);
343 colorTexture.TexImage2D(0, PixelFormat::RGBA8, false, Width, Height, nullptr);
344 RHI::RenderTarget renderTarget;
345 renderTarget.AttachColorTexture(colorTexture, 0);
346 renderTarget.SetDrawBuffers(1);
347 renderTarget.BindDraw();
348
349 RHI::Device::SetupInitialState();
350 RHI::Device::SetViewport(Recti(0, 0, Width, Height));
351 RHI::Device::SetClearColor(Colorf(40.0f / 255.0f, 40.0f / 255.0f, 40.0f / 255.0f, 1.0f));
352 RHI::Device::Clear(ClearFlags::Color);
353
354 const float texRectFull[4] = {1.0f, 0.0f, 1.0f, 0.0f};
355 const float sizeSprite[2] = {64.0f, 48.0f};
356 const float whiteColor[4] = {1.0f, 1.0f, 1.0f, 1.0f};
357 float model[16];
358
359 // Sprite 1: checker, opaque, white modulation -> textured path + clear-outside
360 MakeTranslation(96.0f, 80.0f, model);
361 DrawSprite(program, camera, blocks, checkerTexture, vbo, ibo, model, whiteColor, texRectFull, sizeSprite,
362 false, BlendingFactor::One, BlendingFactor::Zero, nullptr, DrawKind::Arrays);
363
364 // Sprite 2: white texture, opaque, color modulation (1, 0.5, 0.25, 1)
365 const float modColor[4] = {1.0f, 0.5f, 0.25f, 1.0f};
366 MakeTranslation(8.0f, 8.0f, model);
367 DrawSprite(program, camera, blocks, whiteTexture, vbo, ibo, model, modColor, texRectFull, sizeSprite,
368 false, BlendingFactor::One, BlendingFactor::Zero, nullptr, DrawKind::Arrays);
369
370 // Sprite 3: white texture, alpha blend, half-alpha modulation -> blend over the gray clear
371 const float halfAlpha[4] = {1.0f, 1.0f, 1.0f, 0.5f};
372 MakeTranslation(184.0f, 8.0f, model);
373 DrawSprite(program, camera, blocks, whiteTexture, vbo, ibo, model, halfAlpha, texRectFull, sizeSprite,
374 true, BlendingFactor::SrcAlpha, BlendingFactor::OneMinusSrcAlpha, nullptr, DrawKind::Arrays);
375
376 // Sprite 4: checker, opaque, drawn via DrawElements, with a scissor clipping its right half (px < 128)
377 MakeTranslation(96.0f, 176.0f, model);
378 const Recti scissor(0, 0, 128, Height);
379 DrawSprite(program, camera, blocks, checkerTexture, vbo, ibo, model, whiteColor, texRectFull, sizeSprite,
380 false, BlendingFactor::One, BlendingFactor::Zero, &scissor, DrawKind::Elements);
381
382 // --- Read back and assert ---
383 // Drain the tile renderer's deferred draws before touching the texel store directly. The engine's
384 // present/readback paths flush implicitly; the harness bypasses them, and reading (or letting the
385 // test's textures die) with commands still queued reads a stale target - or worse, a later flush
386 // rasterizes commands whose textures are already destroyed.
387 RHI::Software::SwRaster::Flush();
388 const std::uint8_t* pixels = colorTexture.GetPixels();
389 const std::int32_t stride = colorTexture.GetStrideBytes();
390
391 // The render-target store is bottom-up (OpenGL framebuffer convention - see SwRaster::SetColorBuffer's
392 // isFboTarget), so every assertion flips its logical top-down y into a store row
393 auto fy = [&](std::int32_t y) { return Height - 1 - y; };
394
395 std::printf("Software RHI backend harness (%dx%d)\n", Width, Height);
396 std::printf("Sprite 1 - checker quadrants (opaque, white modulation):\n");
397 CheckPixel(pixels, stride, 110, fy(90), 255, 0, 0, 255, 0, "checker top-left = red");
398 CheckPixel(pixels, stride, 145, fy(90), 0, 255, 0, 255, 0, "checker top-right = green");
399 CheckPixel(pixels, stride, 110, fy(116), 0, 0, 255, 255, 0, "checker bottom-left = blue");
400 CheckPixel(pixels, stride, 145, fy(116), 255, 255, 0, 255, 0, "checker bottom-right = yellow");
401
402 std::printf("Clear color outside the sprites:\n");
403 CheckPixel(pixels, stride, 10, fy(130), 40, 40, 40, 255, 0, "clear (left edge)");
404 CheckPixel(pixels, stride, 250, fy(200), 40, 40, 40, 255, 0, "clear (bottom-right)");
405
406 std::printf("Sprite 2 - color modulation (white x (1, 0.5, 0.25)):\n");
407 CheckPixel(pixels, stride, 40, fy(32), 255, 128, 64, 255, 2, "modulated white");
408
409 std::printf("Sprite 3 - alpha blend (half-alpha white over gray 40):\n");
410 CheckPixel(pixels, stride, 216, fy(32), 148, 148, 148, 191, 2, "alpha-blended white");
411
412 std::printf("Sprite 4 - scissor (right half clipped):\n");
413 CheckPixel(pixels, stride, 110, fy(186), 255, 0, 0, 255, 0, "scissor kept = red");
414 CheckPixel(pixels, stride, 145, fy(186), 40, 40, 40, 255, 0, "scissor clipped = clear");
415
416 const bool wrote = WritePng(outputPath, pixels, Width, Height, stride);
417 std::printf("PNG: %s (%s)\n", outputPath, wrote ? "ok" : "FAILED");
418 return wrote;
419 }
420
421 // ============================================================================================
422 // Full-screen procedural effects (TexturedBackground / Combine) and the palette-remap path
423 // ============================================================================================
424
425 // Uploads a full RGBA8 image built by a per-texel callback (helps stage the combine/scene textures)
426 template<class Fn>
427 void UploadRgba(RHI::Texture& texture, std::int32_t w, std::int32_t h, Fn texel)
428 {
429 std::vector<std::uint8_t> data(std::size_t(w) * std::size_t(h) * 4);
430 for (std::int32_t y = 0; y < h; y++) {
431 for (std::int32_t x = 0; x < w; x++) {
432 std::uint8_t* p = data.data() + (std::size_t(y) * w + x) * 4;
433 texel(x, y, p);
434 }
435 }
436 texture.TexImage2D(0, PixelFormat::RGBA8, false, w, h, data.data());
437 }
438
439 // --- TexturedBackground / TexturedBackgroundCircle: solid source -> analytic horizon/edge asserts ---
440
441 bool RunBackgroundTest(const char* baseDir, bool circle)
442 {
443 constexpr std::int32_t W = 256, H = 144; // 16:9, so the shader's aspect correction is exactly 1.0
444 g_uniformBump = 0;
445
446 const ShaderCompiler::Program& prog = (circle ? Jazz2::ShadersGen::TexturedBackgroundCircle : Jazz2::ShadersGen::TexturedBackground);
447 const char* label = (circle ? "TexturedBackgroundCircle" : "TexturedBackground");
448 std::printf("\n=== %s (solid source) ===\n", label);
449
450 RHI::ShaderProgram program(RHI::ShaderProgram::QueryPhase::Immediate);
451 program.SetReflection(&prog.Variants[0]);
452 program.Link(RHI::ShaderProgram::Introspection::Enabled);
453 program.SetObjectLabel(label);
454
455 RHI::Buffer uniformBuffer(BufferTarget::Uniform);
456 uniformBuffer.BufferData(64 * 1024, nullptr, BufferUsage::StreamDraw);
457 g_uniformBuffer = &uniformBuffer;
458 RHI::ShaderUniformBlocks::SetUniformRangeAllocator(&AllocUniformRange);
459
460 std::vector<std::uint8_t> cameraBuffer(program.GetUniformsSize() + 16, 0);
461 RHI::ShaderUniforms camera(&program);
462 camera.SetUniformsDataPointer(cameraBuffer.data());
463 float projection[16];
464 BuildOrtho(W, H, projection);
465 camera.GetUniform("uProjectionMatrix")->SetFloatVector(projection);
466 camera.GetUniform("uViewMatrix")->SetFloatVector(kIdentityView);
467 camera.GetUniform("uViewSize")->SetFloatValue(float(W), float(H));
468 camera.GetUniform("uCameraPos")->SetFloatValue(0.0f, 0.0f);
469 // horizonColor.w = 0 disables the star field, so the horizon band is exactly the horizon colour
470 const float horizon[4] = {0.9f, 0.2f, 0.1f, 0.0f};
471 camera.GetUniform("uHorizonColor")->SetFloatVector(horizon);
472 camera.GetUniform("uShift")->SetFloatValue(0.0f, 0.0f);
473
474 std::vector<std::uint8_t> blockBuffer(program.GetUniformBlocksSize() + 16, 0);
475 RHI::ShaderUniformBlocks blocks(&program);
476 blocks.SetUniformsDataPointer(blockBuffer.data());
477
478 const std::uint8_t solid[4] = {0, 180, 90, 255};
479 RHI::Texture srcTexture(TextureTarget::Texture2D);
480 srcTexture.TexImage2D(0, PixelFormat::RGBA8, false, 1, 1, solid);
481
482 RHI::Buffer vbo(BufferTarget::Vertex);
483 vbo.BufferData(4 * 4 * sizeof(float), nullptr, BufferUsage::StaticDraw);
484 RHI::Buffer ibo(BufferTarget::Index);
485 const std::uint16_t indices[6] = {0, 1, 2, 2, 1, 3};
486 ibo.BufferData(sizeof(indices), indices, BufferUsage::StaticDraw);
487
488 RHI::Texture colorTexture(TextureTarget::Texture2D);
489 colorTexture.TexImage2D(0, PixelFormat::RGBA8, false, W, H, nullptr);
490 RHI::RenderTarget renderTarget;
491 renderTarget.AttachColorTexture(colorTexture, 0);
492 renderTarget.SetDrawBuffers(1);
493 renderTarget.BindDraw();
494
495 RHI::Device::SetupInitialState();
496 RHI::Device::SetViewport(Recti(0, 0, W, H));
497 RHI::Device::SetClearColor(Colorf(0.0f, 0.0f, 0.0f, 1.0f));
498 RHI::Device::Clear(ClearFlags::Color);
499
500 float model[16];
501 MakeTranslation(0.0f, 0.0f, model);
502 auto ib = blocks.GetUniformBlock("InstanceBlock");
503 ib->GetUniform("modelMatrix")->SetFloatVector(model);
504 ib->GetUniform("color")->SetFloatVector(kWhite);
505 ib->GetUniform("texRect")->SetFloatVector(kTexRectFull);
506 ib->GetUniform("spriteSize")->SetFloatValue(float(W), float(H));
507 blocks.CommitUniformBlocks();
508
509 srcTexture.Bind(0);
510 program.Use();
511 blocks.Bind();
512 camera.CommitUniforms();
513 RHI::Device::SetBlendingEnabled(false);
514 RHI::Device::SetScissorTestEnabled(false);
515 program.DefineVertexFormat(&vbo, &ibo, 0);
516 vbo.Bind();
517 RHI::Device::DrawArrays(PrimitiveType::TriangleStrip, 0, 4);
518
519 // Drain the tile renderer's deferred draws before touching the texel store directly. The engine's
520 // present/readback paths flush implicitly; the harness bypasses them, and reading (or letting the
521 // test's textures die) with commands still queued reads a stale target - or worse, a later flush
522 // rasterizes commands whose textures are already destroyed.
523 RHI::Software::SwRaster::Flush();
524 const std::uint8_t* pixels = colorTexture.GetPixels();
525 const std::int32_t stride = colorTexture.GetStrideBytes();
526 const int hr = 230, hg = 51, hb = 26; // round(horizon.rgb * 255)
527
528 if (!circle) {
529 std::printf("Horizon band (vertical centre) = horizon colour:\n");
530 CheckPixel(pixels, stride, 64, 68, hr, hg, hb, 255, 1, "band left");
531 CheckPixel(pixels, stride, 128, 72, hr, hg, hb, 255, 1, "band centre");
532 CheckPixel(pixels, stride, 200, 76, hr, hg, hb, 255, 1, "band right");
533 std::printf("Top/bottom edges (opacity 0) = source texture colour:\n");
534 CheckPixel(pixels, stride, 128, 0, 0, 180, 90, 255, 1, "top edge = texture");
535 CheckPixel(pixels, stride, 128, H - 1, 0, 180, 90, 255, 1, "bottom edge = texture");
536 } else {
537 std::printf("Screen centre (opacity 1) = horizon colour:\n");
538 CheckPixel(pixels, stride, 128, 72, hr, hg, hb, 255, 1, "centre = horizon");
539 std::printf("Screen corner (opacity 0) = source texture colour:\n");
540 CheckPixel(pixels, stride, 2, 2, 0, 180, 90, 255, 1, "corner = texture");
541 }
542
543 char outputPath[512];
544 MakePath(baseDir, (circle ? "sw_background_circle.png" : "sw_background.png"), outputPath, sizeof(outputPath));
545 const bool wrote = WritePng(outputPath, pixels, W, H, stride);
546 std::printf("PNG: %s (%s)\n", outputPath, wrote ? "ok" : "FAILED");
547 return wrote;
548 }
549
550 // --- TexturedBackground with a patterned source: proves the warp varies + dither changes the output ---
551
552 bool RunBackgroundWarpTest(const char* baseDir)
553 {
554 constexpr std::int32_t W = 256, H = 144;
555 g_uniformBump = 0;
556 std::printf("\n=== TexturedBackground / Dither (patterned source, warp) ===\n");
557
558 RHI::ShaderProgram program(RHI::ShaderProgram::QueryPhase::Immediate);
559 program.SetReflection(&Jazz2::ShadersGen::TexturedBackground.Variants[0]);
560 program.Link(RHI::ShaderProgram::Introspection::Enabled);
561
562 RHI::Buffer uniformBuffer(BufferTarget::Uniform);
563 uniformBuffer.BufferData(64 * 1024, nullptr, BufferUsage::StreamDraw);
564 g_uniformBuffer = &uniformBuffer;
565 RHI::ShaderUniformBlocks::SetUniformRangeAllocator(&AllocUniformRange);
566
567 std::vector<std::uint8_t> cameraBuffer(program.GetUniformsSize() + 16, 0);
568 RHI::ShaderUniforms camera(&program);
569 camera.SetUniformsDataPointer(cameraBuffer.data());
570 float projection[16];
571 BuildOrtho(W, H, projection);
572 camera.GetUniform("uProjectionMatrix")->SetFloatVector(projection);
573 camera.GetUniform("uViewMatrix")->SetFloatVector(kIdentityView);
574 camera.GetUniform("uViewSize")->SetFloatValue(float(W), float(H));
575 camera.GetUniform("uCameraPos")->SetFloatValue(0.0f, 0.0f);
576 const float horizon[4] = {0.9f, 0.2f, 0.1f, 0.0f};
577 camera.GetUniform("uHorizonColor")->SetFloatVector(horizon);
578 camera.GetUniform("uShift")->SetFloatValue(0.0f, 0.0f);
579
580 std::vector<std::uint8_t> blockBuffer(program.GetUniformBlocksSize() + 16, 0);
581 RHI::ShaderUniformBlocks blocks(&program);
582 blocks.SetUniformsDataPointer(blockBuffer.data());
583
584 // A distinct per-texel pattern so the warp maps different screen positions to different texels
585 RHI::Texture srcTexture(TextureTarget::Texture2D);
586 UploadRgba(srcTexture, 8, 8, [](std::int32_t x, std::int32_t y, std::uint8_t* p) {
587 p[0] = std::uint8_t((x * 32) & 0xFF);
588 p[1] = std::uint8_t((y * 32) & 0xFF);
589 p[2] = std::uint8_t(((x + y) * 16) & 0xFF);
590 p[3] = 255;
591 });
592
593 RHI::Buffer vbo(BufferTarget::Vertex);
594 vbo.BufferData(4 * 4 * sizeof(float), nullptr, BufferUsage::StaticDraw);
595 RHI::Buffer ibo(BufferTarget::Index);
596 const std::uint16_t indices[6] = {0, 1, 2, 2, 1, 3};
597 ibo.BufferData(sizeof(indices), indices, BufferUsage::StaticDraw);
598
599 RHI::Texture colorTexture(TextureTarget::Texture2D);
600 colorTexture.TexImage2D(0, PixelFormat::RGBA8, false, W, H, nullptr);
601 RHI::RenderTarget renderTarget;
602 renderTarget.AttachColorTexture(colorTexture, 0);
603 renderTarget.SetDrawBuffers(1);
604 renderTarget.BindDraw();
605
606 RHI::Device::SetupInitialState();
607 RHI::Device::SetViewport(Recti(0, 0, W, H));
608 RHI::Device::SetClearColor(Colorf(0.0f, 0.0f, 0.0f, 1.0f));
609
610 float model[16];
611 MakeTranslation(0.0f, 0.0f, model);
612 auto ib = blocks.GetUniformBlock("InstanceBlock");
613 ib->GetUniform("modelMatrix")->SetFloatVector(model);
614 ib->GetUniform("color")->SetFloatVector(kWhite);
615 ib->GetUniform("texRect")->SetFloatVector(kTexRectFull);
616 ib->GetUniform("spriteSize")->SetFloatValue(float(W), float(H));
617
618 const std::uint8_t* pixels = colorTexture.GetPixels();
619 const std::int32_t stride = colorTexture.GetStrideBytes();
620
621 // Every pass drains the tile renderer's deferred draws before the store is read. The engine's
622 // present/readback paths flush implicitly; the harness bypasses them, and reading (or letting the
623 // test's textures die) with commands still queued reads a stale target - or worse, a later flush
624 // (SetTargetBuffer flushes the OLD queue when the next test switches targets) rasterizes commands
625 // whose source texture and destination store are already destroyed - a use-after-free that
626 // corrupted the heap and crashed the run one test later.
627 auto issueDraw = [&](const char* lbl) {
628 program.SetObjectLabel(lbl);
629 blocks.CommitUniformBlocks();
630 srcTexture.Bind(0);
631 program.Use();
632 blocks.Bind();
633 camera.CommitUniforms();
634 RHI::Device::SetBlendingEnabled(false);
635 RHI::Device::SetScissorTestEnabled(false);
636 program.DefineVertexFormat(&vbo, &ibo, 0);
637 vbo.Bind();
638 RHI::Device::DrawArrays(PrimitiveType::TriangleStrip, 0, 4);
639 RHI::Software::SwRaster::Flush();
640 };
641
642 // Non-dither pass, captured for comparison
643 RHI::Device::Clear(ClearFlags::Color);
644 issueDraw("TexturedBackground");
645 std::vector<std::uint8_t> nonDither(pixels, pixels + std::size_t(H) * stride);
646
647 // Dither pass (the PNG)
648 RHI::Device::Clear(ClearFlags::Color);
649 issueDraw("TexturedBackgroundDither");
650
651 std::printf("Horizon band still resolves to the horizon colour:\n");
652 CheckPixel(pixels, stride, 128, H - 1 - 72, 230, 51, 26, 255, 1, "band centre");
653
654 // The warp must sample different texels along a scanline (top row, opacity ~ 0 -> pure texture)
655 int minR = 255, maxR = 0;
656 for (std::int32_t x = 0; x < W; x++) {
657 const std::uint8_t* p = nonDither.data() + std::size_t(4) * stride + std::size_t(x) * 4;
658 if (p[0] < minR) { minR = p[0]; }
659 if (p[0] > maxR) { maxR = p[0]; }
660 }
661 g_checks++;
662 if (maxR - minR > 8) {
663 std::printf(" ok warp varies across scanline (R range %d..%d)\n", minR, maxR);
664 } else {
665 g_failures++;
666 std::printf(" FAIL warp scanline too flat (R range %d..%d)\n", minR, maxR);
667 }
668
669 // The software renderer intentionally DROPS the dither sample (TexturedBackground.shader guards it
670 // with `#ifdef DITHER #ifndef SOFTWARE_RENDERER` - the extra per-pixel texture sample is too costly
671 // on the CPU), so the DITHER variant must resolve to the same generated fragment math and produce a
672 // byte-identical image. This inverts the original "dither changes pixels" assertion, which described
673 // the GPU backends.
674 g_checks++;
675 if (std::memcmp(nonDither.data(), pixels, std::size_t(H) * stride) == 0) {
676 std::printf(" ok dither variant == non-dither (SW drops the dither term by design)\n");
677 } else {
678 int changed = 0;
679 for (std::int32_t y = 0; y < H; y++) {
680 for (std::int32_t x = 0; x < W; x++) {
681 const std::uint8_t* a = nonDither.data() + std::size_t(y) * stride + std::size_t(x) * 4;
682 const std::uint8_t* b = pixels + std::size_t(y) * stride + std::size_t(x) * 4;
683 if (std::memcmp(a, b, 4) != 0) {
684 changed++;
685 }
686 }
687 }
688 g_failures++;
689 std::printf(" FAIL dither variant differs from non-dither in %d pixels (SW should drop dithering)\n", changed);
690 }
691
692 char outputPath[512];
693 MakePath(baseDir, "sw_background_dither.png", outputPath, sizeof(outputPath));
694 const bool wrote = WritePng(outputPath, pixels, W, H, stride);
695 std::printf("PNG: %s (%s)\n", outputPath, wrote ? "ok" : "FAILED");
696 return wrote;
697 }
698
699 // --- Combine (viewport compositor) ---
700 //
701 // The software backend does NOT run a Combine fragment: SwDevice::Dispatch intercepts every draw of a
702 // Combine-labeled program and applies the CPU dynamic-lighting combine the compositor queued for the
703 // viewport (SetPendingSoftwareLighting) in place over the SCREEN back-buffer - with nothing queued the
704 // draw is a no-op. The original shader-compositing assertions (scene x lighting x blur textures) became
705 // stale with that design; this now asserts the device-intercept semantics against a verbatim scalar
706 // reference of the combine loop.
707
708 // Scalar reference of SwDevice::ApplyPendingSoftwareLighting's per-pixel combine (kept verbatim so the
709 // SIMD kernel is checked bit-exactly)
710 static void RefCombineLighting(std::uint8_t* pixels, std::int32_t fbWidth, std::int32_t fbHeight, std::int32_t fbStride,
711 const float* lightmap, std::int32_t lmW, std::int32_t lmH, std::int32_t scale,
712 std::int32_t vpX, std::int32_t vpY, std::int32_t vpW, std::int32_t vpH,
713 float ambR, float ambG, float ambB)
714 {
715 vpX = std::max(0, vpX);
716 vpY = std::max(0, vpY);
717 vpW = std::min(vpW, fbWidth - vpX);
718 vpH = std::min(vpH, fbHeight - vpY);
719 if (vpW <= 0 || vpH <= 0) return;
720 auto clampf = [](float v, float lo, float hi) { return v < lo ? lo : (v > hi ? hi : v); };
721 for (std::int32_t y = 0; y < vpH; y++) {
722 const std::int32_t lmY = std::min(y / scale, lmH - 1);
723 const float* texelBase = lightmap + (std::size_t)lmY * lmW * 2;
724 std::uint8_t* px = pixels + (std::size_t)(vpY + y) * fbStride + (std::size_t)vpX * 4;
725 for (std::int32_t x = 0; x < vpW; x++, px += 4) {
726 const std::int32_t lmX = std::min(x / scale, lmW - 1);
727 const float r = clampf(texelBase[lmX * 2], 0.0f, 1.0f);
728 const float g = clampf(texelBase[lmX * 2 + 1], 0.0f, 1.0f);
729 const float darkT = clampf(1.0f - r, 0.0f, 1.0f);
730 if (darkT <= 0.0f && g <= 0.0f) {
731 continue;
732 }
733 const float lit = 1.0f + g;
734 const float core = (g > 0.7f ? g - 0.7f : 0.0f);
735 float cr = (px[0] / 255.0f) * lit + core;
736 float cg = (px[1] / 255.0f) * lit + core;
737 float cb = (px[2] / 255.0f) * lit + core;
738 cr += (ambR - cr) * darkT;
739 cg += (ambG - cg) * darkT;
740 cb += (ambB - cb) * darkT;
741 px[0] = (std::uint8_t)clampf(cr * 255.0f + 0.5f, 0.0f, 255.0f);
742 px[1] = (std::uint8_t)clampf(cg * 255.0f + 0.5f, 0.0f, 255.0f);
743 px[2] = (std::uint8_t)clampf(cb * 255.0f + 0.5f, 0.0f, 255.0f);
744 }
745 }
746 }
747
748 bool RunCombineTest(const char* baseDir)
749 {
750 constexpr std::int32_t W = 64, H = 64;
751 g_uniformBump = 0;
752 std::printf("\n=== Combine (device-intercepted CPU lighting combine) ===\n");
753
754 RHI::ShaderProgram program(RHI::ShaderProgram::QueryPhase::Immediate);
755 program.SetReflection(&Jazz2::ShadersGen::Combine.Variants[0]);
756 program.Link(RHI::ShaderProgram::Introspection::Enabled);
757 program.SetObjectLabel("Combine");
758
759 RHI::Buffer uniformBuffer(BufferTarget::Uniform);
760 uniformBuffer.BufferData(64 * 1024, nullptr, BufferUsage::StreamDraw);
761 g_uniformBuffer = &uniformBuffer;
762 RHI::ShaderUniformBlocks::SetUniformRangeAllocator(&AllocUniformRange);
763
764 // The intercept composites over the SCREEN back-buffer, not a render target
765 RHI::Software::SwDevice::SetRenderTarget(nullptr);
766 RHI::Software::SwDevice::ResizeScreenFramebuffer(W, H);
767 RHI::Software::Framebuffer fb = RHI::Software::SwDevice::GetScreenFramebuffer();
768 g_checks++;
769 if (fb.pixels == nullptr) {
770 g_failures++;
771 std::printf(" FAIL no screen framebuffer\n");
772 return false;
773 }
774 std::printf(" ok screen framebuffer %dx%d\n", fb.width, fb.height);
775
776 // Deterministic scene in the back-buffer
777 for (std::int32_t y = 0; y < H; y++) {
778 for (std::int32_t x = 0; x < W; x++) {
779 std::uint8_t* p = fb.pixels + std::size_t(y) * fb.strideBytes + std::size_t(x) * 4;
780 p[0] = std::uint8_t((x * 4) & 0xFF);
781 p[1] = std::uint8_t((y * 4) & 0xFF);
782 p[2] = std::uint8_t(((x + y) * 2) & 0xFF);
783 p[3] = 255;
784 }
785 }
786 std::vector<std::uint8_t> expected(fb.pixels, fb.pixels + std::size_t(H) * fb.strideBytes);
787
788 RHI::Device::SetupInitialState();
789 RHI::Device::SetViewport(Recti(0, 0, W, H));
790 RHI::Device::SetBlendingEnabled(false);
791 RHI::Device::SetScissorTestEnabled(false);
792 program.Use();
793
794 // 1: a Combine draw with NO queued lighting must leave the buffer untouched (no-op intercept)
795 RHI::Device::DrawArrays(PrimitiveType::TriangleStrip, 0, 4);
796 g_checks++;
797 if (std::memcmp(fb.pixels, expected.data(), expected.size()) == 0) {
798 std::printf(" ok no queued lighting -> buffer untouched\n");
799 } else {
800 g_failures++;
801 std::printf(" FAIL no queued lighting modified the buffer\n");
802 }
803
804 // 2: queue a lightmap covering lit / clamped / half+glow / dark / negative regimes, draw, and
805 // compare the whole buffer against the scalar reference
806 constexpr std::int32_t lmW = 32, lmH = 32, scale = 2;
807 std::vector<float> lightmap(std::size_t(lmW) * lmH * 2);
808 for (std::int32_t ty = 0; ty < lmH; ty++) {
809 for (std::int32_t tx = 0; tx < lmW; tx++) {
810 float* t = lightmap.data() + (std::size_t(ty) * lmW + tx) * 2;
811 if (tx < 6) { t[0] = 1.0f; t[1] = 0.0f; } // fully lit -> untouched
812 else if (tx < 12) { t[0] = 1.4f; t[1] = -0.3f; } // out-of-range, clamps to lit
813 else if (tx < 18) { t[0] = 0.5f; t[1] = 0.9f; } // half lit + glow core (g > 0.7)
814 else if (tx < 24) { t[0] = 0.5f; t[1] = 0.7f; } // half lit, g == 0.7 (no core)
815 else { t[0] = 0.0f; t[1] = 0.0f; } // dark -> ambient
816 }
817 }
818 const float ambR = 0.15f, ambG = 0.10f, ambB = 0.30f;
819 RefCombineLighting(expected.data(), fb.width, fb.height, fb.strideBytes, lightmap.data(), lmW, lmH, scale, 0, 0, W, H, ambR, ambG, ambB);
820 RHI::Software::SwDevice::SetPendingSoftwareLighting(lightmap.data(), lmW, lmH, scale, 0, 0, W, H, ambR, ambG, ambB);
821 RHI::Device::DrawArrays(PrimitiveType::TriangleStrip, 0, 4);
822
823 std::size_t diffs = 0;
824 std::int32_t firstX = -1, firstY = -1;
825 for (std::int32_t y = 0; y < H; y++) {
826 for (std::int32_t i = 0; i < W * 4; i++) {
827 if (fb.pixels[std::size_t(y) * fb.strideBytes + i] != expected[std::size_t(y) * fb.strideBytes + i]) {
828 if (diffs == 0) { firstX = i / 4; firstY = y; }
829 diffs++;
830 }
831 }
832 }
833 g_checks++;
834 if (diffs == 0) {
835 std::printf(" ok queued lighting combine == scalar reference (%dx%d, scale %d)\n", W, H, scale);
836 } else {
837 g_failures++;
838 std::printf(" FAIL combine differs from reference: %zu bytes (first at %d,%d)\n", diffs, firstX, firstY);
839 }
840
841 // 3: the queue must be consumed - a further draw with nothing queued is a no-op again
842 std::vector<std::uint8_t> afterCombine(fb.pixels, fb.pixels + std::size_t(H) * fb.strideBytes);
843 RHI::Device::DrawArrays(PrimitiveType::TriangleStrip, 0, 4);
844 g_checks++;
845 if (std::memcmp(fb.pixels, afterCombine.data(), afterCombine.size()) == 0) {
846 std::printf(" ok queue consumed - next Combine draw is a no-op\n");
847 } else {
848 g_failures++;
849 std::printf(" FAIL lighting queue not consumed by the Combine draw\n");
850 }
851
852 char outputPath[512];
853 MakePath(baseDir, "sw_combine.png", outputPath, sizeof(outputPath));
854 const bool wrote = WritePng(outputPath, fb.pixels, W, H, fb.strideBytes);
855 std::printf("PNG: %s (%s)\n", outputPath, wrote ? "ok" : "FAILED");
856 return wrote;
857 }
858
859 // --- PaletteRemap / BatchedPaletteRemap (the gameplay-critical index -> palette path) ---
860
861 bool RunPaletteTest(const char* baseDir)
862 {
863 constexpr std::int32_t W = 64, H = 64;
864 g_uniformBump = 0;
865 std::printf("\n=== PaletteRemap / BatchedPaletteRemap ===\n");
866
867 RHI::Buffer uniformBuffer(BufferTarget::Uniform);
868 uniformBuffer.BufferData(64 * 1024, nullptr, BufferUsage::StreamDraw);
869 g_uniformBuffer = &uniformBuffer;
870 RHI::ShaderUniformBlocks::SetUniformRangeAllocator(&AllocUniformRange);
871
872 // 256x256 palette texture, matching the engine's shared palette store (the fragment maps the flat
873 // palette index into a 256x256 texture: palY = floor(palIndex / 256) / 256, so a shorter texture
874 // would fold every row back onto row 0). Row 0 and row 1 hold two distinct 256-colour palettes.
875 RHI::Texture paletteTexture(TextureTarget::Texture2D);
876 UploadRgba(paletteTexture, 256, 256, [](std::int32_t x, std::int32_t y, std::uint8_t* p) {
877 if (y == 0) {
878 if (x == 0) { p[0] = 0; p[1] = 0; p[2] = 0; p[3] = 0; } // index 0 = transparent
879 else { p[0] = std::uint8_t(x); p[1] = std::uint8_t(255 - x); p[2] = 128; p[3] = 255; }
880 } else {
881 p[0] = std::uint8_t(255 - x); p[1] = std::uint8_t(x); p[2] = 64; p[3] = 255;
882 }
883 });
884
885 // R8 index sprite: index = column * 16 (0, 16, ... 240), uniform down each column
886 RHI::Texture indexTexture(TextureTarget::Texture2D);
887 {
888 std::vector<std::uint8_t> data(16 * 16);
889 for (std::int32_t y = 0; y < 16; y++) {
890 for (std::int32_t x = 0; x < 16; x++) {
891 data[std::size_t(y) * 16 + x] = std::uint8_t((x * 16) & 0xFF);
892 }
893 }
894 indexTexture.TexImage2D(0, PixelFormat::R8, false, 16, 16, data.data());
895 }
896
897 RHI::Buffer vbo(BufferTarget::Vertex);
898 vbo.BufferData(4 * 4 * sizeof(float), nullptr, BufferUsage::StaticDraw);
899 RHI::Buffer ibo(BufferTarget::Index);
900 const std::uint16_t indices6[6] = {0, 1, 2, 2, 1, 3};
901 ibo.BufferData(sizeof(indices6), indices6, BufferUsage::StaticDraw);
902
903 RHI::Texture colorTexture(TextureTarget::Texture2D);
904 colorTexture.TexImage2D(0, PixelFormat::RGBA8, false, W, H, nullptr);
905 RHI::RenderTarget renderTarget;
906 renderTarget.AttachColorTexture(colorTexture, 0);
907 renderTarget.SetDrawBuffers(1);
908 renderTarget.BindDraw();
909
910 // Drain the tile renderer's deferred draws before touching the texel store directly. The engine's
911 // present/readback paths flush implicitly; the harness bypasses them, and reading (or letting the
912 // test's textures die) with commands still queued reads a stale target - or worse, a later flush
913 // rasterizes commands whose textures are already destroyed.
914 RHI::Software::SwRaster::Flush();
915 const std::uint8_t* pixels = colorTexture.GetPixels();
916 const std::int32_t stride = colorTexture.GetStrideBytes();
917 bool wroteAll = true;
918
919 // ---- Draw 1: single PaletteRemap, palette row 0, opaque, white modulation ----
920 {
921 RHI::ShaderProgram program(RHI::ShaderProgram::QueryPhase::Immediate);
922 program.SetReflection(&Jazz2::ShadersGen::PaletteRemap.Variants[0]);
923 program.Link(RHI::ShaderProgram::Introspection::Enabled);
924 program.SetObjectLabel("PaletteRemap");
925
926 std::vector<std::uint8_t> cameraBuffer(program.GetUniformsSize() + 16, 0);
927 RHI::ShaderUniforms camera(&program);
928 camera.SetUniformsDataPointer(cameraBuffer.data());
929 float projection[16];
930 BuildOrtho(W, H, projection);
931 camera.GetUniform("uProjectionMatrix")->SetFloatVector(projection);
932 camera.GetUniform("uViewMatrix")->SetFloatVector(kIdentityView);
933
934 std::vector<std::uint8_t> blockBuffer(program.GetUniformBlocksSize() + 16, 0);
935 RHI::ShaderUniformBlocks blocks(&program);
936 blocks.SetUniformsDataPointer(blockBuffer.data());
937
938 RHI::Device::SetupInitialState();
939 RHI::Device::SetViewport(Recti(0, 0, W, H));
940 RHI::Device::SetClearColor(Colorf(40.0f / 255.0f, 40.0f / 255.0f, 40.0f / 255.0f, 1.0f));
941 RHI::Device::Clear(ClearFlags::Color);
942
943 float model[16];
944 MakeTranslation(0.0f, 0.0f, model);
945 const float size[2] = {float(W), float(H)};
946 auto ib = blocks.GetUniformBlock("InstanceBlock");
947 ib->GetUniform("modelMatrix")->SetFloatVector(model);
948 ib->GetUniform("color")->SetFloatVector(kWhite);
949 ib->GetUniform("texRect")->SetFloatVector(kTexRectFull);
950 ib->GetUniform("spriteSize")->SetFloatVector(size);
951 ib->GetUniform("palOffset")->SetFloatValue(0.0f);
952 blocks.CommitUniformBlocks();
953
954 indexTexture.Bind(0);
955 paletteTexture.Bind(1);
956 program.Use();
957 blocks.Bind();
958 camera.CommitUniforms();
959 RHI::Device::SetBlendingEnabled(false);
960 RHI::Device::SetScissorTestEnabled(false);
961 program.DefineVertexFormat(&vbo, &ibo, 0);
962 vbo.Bind();
963 RHI::Device::DrawArrays(PrimitiveType::TriangleStrip, 0, 4);
964 RHI::Software::SwRaster::Flush(); // Drain the deferred tiles before asserting texels
965
966 std::printf("Row 0 lookups (opaque, white):\n");
967 CheckPixel(pixels, stride, 2, 10, 0, 0, 0, 0, 0, "index 0 = transparent entry");
968 CheckPixel(pixels, stride, 6, 10, 16, 239, 128, 255, 1, "index 16");
969 CheckPixel(pixels, stride, 34, 10, 128, 127, 128, 255, 1, "index 128");
970 CheckPixel(pixels, stride, 62, 10, 240, 15, 128, 255, 1, "index 240");
971
972 char outputPath[512];
973 MakePath(baseDir, "sw_palette.png", outputPath, sizeof(outputPath));
974 const bool wrote = WritePng(outputPath, pixels, W, H, stride);
975 std::printf("PNG: %s (%s)\n", outputPath, wrote ? "ok" : "FAILED");
976 wroteAll = wroteAll && wrote;
977 }
978
979 // ---- Draw 2: single PaletteRemap, palette row 1 (offset 256), colour modulation ----
980 {
981 RHI::ShaderProgram program(RHI::ShaderProgram::QueryPhase::Immediate);
982 program.SetReflection(&Jazz2::ShadersGen::PaletteRemap.Variants[0]);
983 program.Link(RHI::ShaderProgram::Introspection::Enabled);
984 program.SetObjectLabel("PaletteRemap");
985
986 std::vector<std::uint8_t> cameraBuffer(program.GetUniformsSize() + 16, 0);
987 RHI::ShaderUniforms camera(&program);
988 camera.SetUniformsDataPointer(cameraBuffer.data());
989 float projection[16];
990 BuildOrtho(W, H, projection);
991 camera.GetUniform("uProjectionMatrix")->SetFloatVector(projection);
992 camera.GetUniform("uViewMatrix")->SetFloatVector(kIdentityView);
993
994 std::vector<std::uint8_t> blockBuffer(program.GetUniformBlocksSize() + 16, 0);
995 RHI::ShaderUniformBlocks blocks(&program);
996 blocks.SetUniformsDataPointer(blockBuffer.data());
997
998 RHI::Device::SetClearColor(Colorf(40.0f / 255.0f, 40.0f / 255.0f, 40.0f / 255.0f, 1.0f));
999 RHI::Device::Clear(ClearFlags::Color);
1000
1001 float model[16];
1002 MakeTranslation(0.0f, 0.0f, model);
1003 const float size[2] = {float(W), float(H)};
1004 const float modColor[4] = {1.0f, 0.5f, 1.0f, 1.0f};
1005 auto ib = blocks.GetUniformBlock("InstanceBlock");
1006 ib->GetUniform("modelMatrix")->SetFloatVector(model);
1007 ib->GetUniform("color")->SetFloatVector(modColor);
1008 ib->GetUniform("texRect")->SetFloatVector(kTexRectFull);
1009 ib->GetUniform("spriteSize")->SetFloatVector(size);
1010 ib->GetUniform("palOffset")->SetFloatValue(256.0f);
1011 blocks.CommitUniformBlocks();
1012
1013 indexTexture.Bind(0);
1014 paletteTexture.Bind(1);
1015 program.Use();
1016 blocks.Bind();
1017 camera.CommitUniforms();
1018 RHI::Device::SetBlendingEnabled(false);
1019 RHI::Device::SetScissorTestEnabled(false);
1020 program.DefineVertexFormat(&vbo, &ibo, 0);
1021 vbo.Bind();
1022 RHI::Device::DrawArrays(PrimitiveType::TriangleStrip, 0, 4);
1023 RHI::Software::SwRaster::Flush(); // Drain the deferred tiles before asserting texels
1024
1025 std::printf("Row 1 lookups (offset 256) with colour modulation (1, 0.5, 1):\n");
1026 CheckPixel(pixels, stride, 6, 10, 239, 8, 64, 255, 1, "row 1 index 16 x mod");
1027 CheckPixel(pixels, stride, 34, 10, 127, 64, 64, 255, 1, "row 1 index 128 x mod");
1028 }
1029
1030 // ---- Draw 3: BatchedPaletteRemap, two instances (row 0 left half, row 1 right half) ----
1031 {
1032 RHI::ShaderProgram program(RHI::ShaderProgram::QueryPhase::Immediate);
1033 program.SetBatchSize(2);
1034 program.SetReflection(&Jazz2::ShadersGen::BatchedPaletteRemap.Variants[0]);
1035 program.Link(RHI::ShaderProgram::Introspection::Enabled);
1036 program.SetObjectLabel("BatchedPaletteRemap");
1037
1038 std::vector<std::uint8_t> cameraBuffer(program.GetUniformsSize() + 16, 0);
1039 RHI::ShaderUniforms camera(&program);
1040 camera.SetUniformsDataPointer(cameraBuffer.data());
1041 float projection[16];
1042 BuildOrtho(W, H, projection);
1043 camera.GetUniform("uProjectionMatrix")->SetFloatVector(projection);
1044 camera.GetUniform("uViewMatrix")->SetFloatVector(kIdentityView);
1045
1046 std::vector<std::uint8_t> blockBuffer(program.GetUniformBlocksSize() + 16, 0);
1047 RHI::ShaderUniformBlocks blocks(&program);
1048 blocks.SetUniformsDataPointer(blockBuffer.data());
1049
1050 RHI::Device::SetClearColor(Colorf(40.0f / 255.0f, 40.0f / 255.0f, 40.0f / 255.0f, 1.0f));
1051 RHI::Device::Clear(ClearFlags::Color);
1052
1053 // Instance 0: left half [0,32) using palette row 0; instance 1: right half [32,64) using row 1
1054 float model0[16], model1[16];
1055 MakeTranslation(0.0f, 0.0f, model0);
1056 MakeTranslation(32.0f, 0.0f, model1);
1057 const float sizeHalf[2] = {32.0f, float(H)};
1058 FillInstanceRaw(blockBuffer.data() + 0, model0, kWhite, kTexRectFull, sizeHalf, 0.0f);
1059 FillInstanceRaw(blockBuffer.data() + 112, model1, kWhite, kTexRectFull, sizeHalf, 256.0f);
1060 blocks.CommitUniformBlocks();
1061
1062 indexTexture.Bind(0);
1063 paletteTexture.Bind(1);
1064 program.Use();
1065 blocks.Bind();
1066 camera.CommitUniforms();
1067 RHI::Device::SetBlendingEnabled(false);
1068 RHI::Device::SetScissorTestEnabled(false);
1069 program.DefineVertexFormat(&vbo, &ibo, 0);
1070 vbo.Bind();
1071 RHI::Buffer ibo12(BufferTarget::Index);
1072 const std::uint16_t indices12[12] = {0, 1, 2, 2, 1, 3, 0, 1, 2, 2, 1, 3};
1073 ibo12.BufferData(sizeof(indices12), indices12, BufferUsage::StaticDraw);
1074 ibo12.Bind();
1075 RHI::Device::DrawElements(PrimitiveType::Triangles, 12, 0, 0);
1076 RHI::Software::SwRaster::Flush(); // Drain the deferred tiles before asserting texels
1077
1078 std::printf("Batched: left half = row 0, right half = row 1 (index 48 in each):\n");
1079 CheckPixel(pixels, stride, 6, 10, 48, 207, 128, 255, 1, "instance 0 row 0 index 48");
1080 CheckPixel(pixels, stride, 38, 10, 207, 48, 64, 255, 1, "instance 1 row 1 index 48");
1081
1082 char outputPath[512];
1083 MakePath(baseDir, "sw_palette_batched.png", outputPath, sizeof(outputPath));
1084 const bool wrote = WritePng(outputPath, pixels, W, H, stride);
1085 std::printf("PNG: %s (%s)\n", outputPath, wrote ? "ok" : "FAILED");
1086 wroteAll = wroteAll && wrote;
1087 }
1088
1089 // ---- Draw 4: PaletteRemap with an RG8 index (alpha carried in G), alpha-blended over the clear ----
1090 {
1091 RHI::Texture rgTexture(TextureTarget::Texture2D);
1092 {
1093 std::vector<std::uint8_t> data(std::size_t(16) * 16 * 2);
1094 for (std::int32_t y = 0; y < 16; y++) {
1095 for (std::int32_t x = 0; x < 16; x++) {
1096 std::uint8_t* p = data.data() + (std::size_t(y) * 16 + x) * 2;
1097 p[0] = std::uint8_t((x * 16) & 0xFF); // index
1098 p[1] = std::uint8_t(x == 0 ? 0 : (x % 2 ? 128 : 255)); // alpha in G
1099 }
1100 }
1101 rgTexture.TexImage2D(0, PixelFormat::RG8, false, 16, 16, data.data());
1102 // The engine samples RG8 index textures with `.a` mapped to green (ContentResolver sets this
1103 // swizzle on every RG8 index upload); without it the expanded texel's opaque byte 3 is read
1104 rgTexture.SetSwizzle(SwizzleChannel::Red, SwizzleChannel::Green, SwizzleChannel::Blue, SwizzleChannel::Green);
1105 }
1106
1107 RHI::ShaderProgram program(RHI::ShaderProgram::QueryPhase::Immediate);
1108 program.SetReflection(&Jazz2::ShadersGen::PaletteRemap.Variants[0]);
1109 program.Link(RHI::ShaderProgram::Introspection::Enabled);
1110 program.SetObjectLabel("PaletteRemap");
1111
1112 std::vector<std::uint8_t> cameraBuffer(program.GetUniformsSize() + 16, 0);
1113 RHI::ShaderUniforms camera(&program);
1114 camera.SetUniformsDataPointer(cameraBuffer.data());
1115 float projection[16];
1116 BuildOrtho(W, H, projection);
1117 camera.GetUniform("uProjectionMatrix")->SetFloatVector(projection);
1118 camera.GetUniform("uViewMatrix")->SetFloatVector(kIdentityView);
1119
1120 std::vector<std::uint8_t> blockBuffer(program.GetUniformBlocksSize() + 16, 0);
1121 RHI::ShaderUniformBlocks blocks(&program);
1122 blocks.SetUniformsDataPointer(blockBuffer.data());
1123
1124 RHI::Device::SetClearColor(Colorf(40.0f / 255.0f, 40.0f / 255.0f, 40.0f / 255.0f, 1.0f));
1125 RHI::Device::Clear(ClearFlags::Color);
1126
1127 float model[16];
1128 MakeTranslation(0.0f, 0.0f, model);
1129 const float size[2] = {float(W), float(H)};
1130 auto ib = blocks.GetUniformBlock("InstanceBlock");
1131 ib->GetUniform("modelMatrix")->SetFloatVector(model);
1132 ib->GetUniform("color")->SetFloatVector(kWhite);
1133 ib->GetUniform("texRect")->SetFloatVector(kTexRectFull);
1134 ib->GetUniform("spriteSize")->SetFloatVector(size);
1135 ib->GetUniform("palOffset")->SetFloatValue(0.0f);
1136 blocks.CommitUniformBlocks();
1137
1138 rgTexture.Bind(0);
1139 paletteTexture.Bind(1);
1140 program.Use();
1141 blocks.Bind();
1142 camera.CommitUniforms();
1143 RHI::Device::SetBlendingEnabled(true);
1144 RHI::Device::SetBlendingFactors(BlendingFactor::SrcAlpha, BlendingFactor::OneMinusSrcAlpha, BlendingFactor::One, BlendingFactor::OneMinusSrcAlpha);
1145 RHI::Device::SetScissorTestEnabled(false);
1146 program.DefineVertexFormat(&vbo, &ibo, 0);
1147 vbo.Bind();
1148 RHI::Device::DrawArrays(PrimitiveType::TriangleStrip, 0, 4);
1149 RHI::Software::SwRaster::Flush(); // Drain the deferred tiles before asserting texels
1150
1151 // index 16 with G = 128 alpha, palette[0][16] = (16,239,128), blended over the (40,40,40) clear
1152 const float sa = 128.0f / 255.0f;
1153 const int er = int(16 * sa + 40 * (1 - sa) + 0.5f);
1154 const int eg = int(239 * sa + 40 * (1 - sa) + 0.5f);
1155 const int eb = int(128 * sa + 40 * (1 - sa) + 0.5f);
1156 const int ea = int(128 * sa + 255 * (1 - sa) + 0.5f);
1157 std::printf("RG8 index (alpha in G), alpha-blended over the clear:\n");
1158 CheckPixel(pixels, stride, 2, 10, 40, 40, 40, 255, 1, "index 0 (G=0) = clear shows through");
1159 CheckPixel(pixels, stride, 6, 10, er, eg, eb, ea, 2, "index 16 (G=128) blended");
1160 }
1161
1162 return wroteAll;
1163 }
1164
1165 int main(int argc, char** argv)
1166 {
1167 // Unbuffered stdout so a crash in a later test cannot swallow the log of the earlier ones
1168 std::setvbuf(stdout, nullptr, _IONBF, 0);
1169 const char* baseDir = (argc > 1 ? argv[1] : ".");
1170
1171 std::printf("Software RHI backend harness\n");
1172 std::printf("Output directory: %s\n", baseDir);
1173
1174 bool wroteAll = true;
1175 wroteAll = RunSpriteTest(baseDir) && wroteAll;
1176 wroteAll = RunBackgroundTest(baseDir, false) && wroteAll;
1177 wroteAll = RunBackgroundTest(baseDir, true) && wroteAll;
1178 wroteAll = RunBackgroundWarpTest(baseDir) && wroteAll;
1179 wroteAll = RunCombineTest(baseDir) && wroteAll;
1180 wroteAll = RunPaletteTest(baseDir) && wroteAll;
1181
1182 std::printf("\n=====================================\n");
1183 std::printf("Total checks: %d, failures: %d, all PNGs written: %s\n", g_checks, g_failures, wroteAll ? "yes" : "no");
1184
1185 return (g_failures == 0 && wroteAll) ? 0 : 1;
1186 }