Debian Codegraph @

Sources/nCine/Graphics/RHI/Software/SwTileRenderer.h

raw
1 #pragma once
2
3 #if defined(WITH_RHI_SOFTWARE)
4
5 #include "SwRaster.h"
6
7 #include <Containers/SmallVector.h>
8
9 #if defined(WITH_THREADS)
10 # include "../../../Threading/Thread.h"
11 # include "../../../Threading/ThreadSync.h"
12 #endif
13
14 #include <cstdint>
15
16 namespace nCine::RHI::Software
17 {
18 /**
19 @brief Tile-based deferred rasterization layer sitting in front of @ref SwRaster
20
21 Collects the frame's draw calls instead of rasterizing them immediately, then processes the
22 destination surface one small tile at a time so each tile's working set stays resident in the L1
23 data cache while every command that touches it is drawn. On a build with `WITH_THREADS` the tiles
24 are handed out to a pool of worker threads through an atomic counter, so the flush scales across
25 cores; without threads it falls back to a sequential single-pass loop.
26
27 The layer is transparent to the device: @ref SwRaster forwards each draw to @ref SubmitCommand(),
28 which either accepts it for deferral (returning `true`) or declines it (returning `false`) so the
29 caller runs it through the immediate rasterizer instead. @ref Flush() is called before the surface
30 is read back (present) or a different render target is bound, and it never returns until every
31 worker has finished writing, so the pixels are complete and race-free by the time it does.
32 */
33 namespace SwTileRenderer
34 {
35 /** @brief Tile edge length in pixels (`32*32*4` = 4 KB fits comfortably in a 32 KB L1 data cache) */
36 static constexpr std::int32_t TileSize = 32;
37 /** @brief `log2(TileSize)`, used to turn pixel coordinates into tile coordinates with a shift */
38 static constexpr std::int32_t TileSizeShift = 5;
39 /**
40 @brief Upper bound on the commands deferred in one flush window
41
42 A flush threshold, not a static allocation: the command arena grows on demand (geometrically,
43 retaining capacity across frames), so a typical frame only ever allocates as many ~900-byte
44 command slots as it actually submits at once - instead of the former fixed 4096-slot (~3.6 MB)
45 static array sized for the worst case. Hitting the bound flushes and reuses the arena.
46 */
47 static constexpr std::int32_t MaxCommands = 4096;
48
49 /**
50 @brief Sanity ceiling on a destination surface edge
51
52 The tile-bin table is sized dynamically from the actual destination (a 720x405 target needs
53 ~300 bins, not the ~8160 a statically 4K-sized table held), so this is only a guard against a
54 nonsensical target disabling the layer, not a supported-resolution limit.
55 */
56 static constexpr std::int32_t MaxSurfaceDimension = 8192;
57
58 /**
59 @brief Submit-time precomputed state of a procedural sprite-quad command
60
61 Everything a quad command re-derived per tile before is computed once in
62 @ref SubmitCommand() (via `TileInternal::PrepareQuad`) and carried here: the four transformed
63 screen-space vertices (the exact @c FetchVertex output, including the pixel snap), the
64 texture / tint / blend derivation shared by both quad rasterizers, and the axis-aligned or
65 affine setup (fixed-point UV steps resp. UV gradients and edge-function increments). A
66 full-screen quad at 720p used to redo all of this ~900x per flush - once per binned tile.
67 Only the tile/scissor clip and the per-row state remain per-tile, computed from these fields
68 with the identical expressions, so the rasterized pixels are bit-identical.
69
70 `valid == false` marks a command the tile path treats as a no-op (a degenerate quad the
71 rasterizers would reject) or a non-quad command that takes the generic primitive path.
72 */
73 struct PreparedQuad
74 {
75 /** @brief Whether the fields below are filled (procedural quad); `false` = generic path / no-op */
76 bool valid;
77 /** @brief Whether the quad is axis-aligned (selects the axis-aligned or the affine rasterizer) */
78 bool axisAligned;
79 /** @brief The four transformed screen-space vertices (exact `FetchVertex` output, snap included) */
80 Vertex2D v[4];
81
82 // -- Shared derived state (both quad rasterizers) --
83
84 /** @brief Level-0 texel base of the sampled texture, or `nullptr` for an untextured draw */
85 const std::uint8_t* texPixels;
86 /** @brief Sampled texture width in texels (0 when untextured) */
87 std::int32_t texW;
88 /** @brief Sampled texture height in texels (0 when untextured) */
89 std::int32_t texH;
90 /** @brief Byte size of one stored texel (@ref SwTexture stores R8/RG8 natively; 4 when untextured) */
91 std::int32_t texBpp;
92 /** @brief Horizontal wrap mode of the sampled texture */
93 nCine::SamplerWrapping wrapS;
94 /** @brief Vertical wrap mode of the sampled texture */
95 nCine::SamplerWrapping wrapT;
96 /** @brief Whether the texture is sampled bilinearly */
97 bool useLinear;
98 /** @brief Tint red in `[0, 255]` */
99 std::int32_t tR;
100 /** @brief Tint green in `[0, 255]` */
101 std::int32_t tG;
102 /** @brief Tint blue in `[0, 255]` */
103 std::int32_t tB;
104 /** @brief Tint alpha in `[0, 255]` */
105 std::int32_t tA;
106 /** @brief Whether the tint is a full-white no-op */
107 bool whiteTint;
108 /** @brief Whether blending is enabled */
109 bool useBlend;
110 /** @brief Whether the blend factors are the SrcAlpha / OneMinusSrcAlpha fast pair */
111 bool useFastBlend;
112 /** @brief Whether the draw is a constant-color solid fill (no texture, constant fragment output) */
113 bool constantFill;
114 /** @brief The constant fill color (the fragment's packed output), valid when @ref constantFill */
115 std::uint8_t constColor[4];
116
117 // -- Axis-aligned setup (valid when axisAligned) --
118
119 /** @brief Screen-space bounding box minimum X */
120 float fxMin;
121 /** @brief Screen-space bounding box maximum X */
122 float fxMax;
123 /** @brief Screen-space bounding box minimum Y */
124 float fyMin;
125 /** @brief Screen-space bounding box maximum Y */
126 float fyMax;
127 /** @brief Bounding box width (`fxMax - fxMin`) */
128 float fullW;
129 /** @brief Bounding box height (`fyMax - fyMin`) */
130 float fullH;
131 /** @brief U at the left edge */
132 float uLeft;
133 /** @brief U at the right edge */
134 float uRight;
135 /** @brief V at the top edge */
136 float vTop;
137 /** @brief V at the bottom edge */
138 float vBot;
139 /** @brief Texture width in 16.16 fixed point */
140 std::int32_t texWFix;
141 /** @brief Horizontal fixed-point UV step per pixel */
142 std::int32_t dtxFix;
143 /** @brief Vertical fixed-point UV step per pixel */
144 std::int32_t dtyFix;
145 /** @brief Whether the horizontal wrap is Repeat */
146 bool useRepeatS;
147 /** @brief Whether the vertical wrap is Repeat */
148 bool useRepeatT;
149 /** @brief Whether the horizontal wrap is ClampToEdge */
150 bool useClampS;
151 /** @brief Whether the scanline-buffer (gather + SIMD blend) path applies */
152 bool useScanBuf;
153
154 // -- Affine setup (valid when !axisAligned) --
155
156 /** @brief Affine UV gradient du/dx */
157 float dudx;
158 /** @brief Affine UV gradient du/dy */
159 float dudy;
160 /** @brief Affine UV gradient dv/dx */
161 float dvdx;
162 /** @brief Affine UV gradient dv/dy */
163 float dvdy;
164 /** @brief Per-pixel edge-function increments of triangle 1 (v0, v1, v2) */
165 float t1w0dx, t1w1dx, t1w2dx;
166 /** @brief Per-pixel edge-function increments of triangle 2 (v2, v1, v3) */
167 float t2w0dx, t2w1dx, t2w2dx;
168 /** @brief Whether triangle 1 has non-degenerate area */
169 bool tri1Valid;
170 /** @brief Whether triangle 2 has non-degenerate area */
171 bool tri2Valid;
172 /** @brief Sign of triangle 1's area (coverage-test orientation) */
173 bool sign1;
174 /** @brief Sign of triangle 2's area */
175 bool sign2;
176 /** @brief du/dx in 16.16 fixed point, premultiplied by the texture width */
177 std::int32_t dudxFix;
178 /** @brief dv/dx in 16.16 fixed point, premultiplied by the texture height */
179 std::int32_t dvdxFix;
180 };
181
182 /**
183 @brief One deferred draw call together with its pre-computed screen-space bounds
184
185 A snapshot of the @ref DrawContext plus the primitive range and the viewport that was active when
186 the command was submitted, so the worker can reproduce the exact vertex transform later on another
187 thread. The screen-space AABB (inclusive pixel bounds) drives tile binning.
188 */
189 struct DeferredCommand
190 {
191 /** @brief Snapshot of the per-draw context (textures, fixed-function state, blend / scissor) */
192 DrawContext ctx;
193 /** @brief Primitive topology of the deferred range */
194 PrimitiveType primType;
195 /** @brief Index of the first vertex */
196 std::int32_t firstVertex;
197 /** @brief Number of vertices */
198 std::int32_t count;
199
200 /** @brief Viewport origin X at submit time (for the correct NDC-to-screen transform) */
201 std::int32_t viewportX;
202 /** @brief Viewport origin Y at submit time */
203 std::int32_t viewportY;
204 /** @brief Viewport width at submit time */
205 std::int32_t viewportW;
206 /** @brief Viewport height at submit time */
207 std::int32_t viewportH;
208
209 /** @brief Inclusive screen-space AABB minimum X used for tile binning */
210 std::int32_t screenMinX;
211 /** @brief Inclusive screen-space AABB minimum Y */
212 std::int32_t screenMinY;
213 /** @brief Inclusive screen-space AABB maximum X */
214 std::int32_t screenMaxX;
215 /** @brief Inclusive screen-space AABB maximum Y */
216 std::int32_t screenMaxY;
217
218 /**
219 * @brief Whether the AABB was computed from real geometry (procedural sprite quad) rather than
220 * given conservative full-frame bounds. The read-back-skip optimization may only fire when `true`.
221 */
222 bool boundsAreAccurate;
223
224 /**
225 * @brief Whether the command overwrites every pixel of its cover rectangle regardless of what the
226 * destination held before it
227 *
228 * Set at submit time for an axis-aligned procedural quad whose write is destination-independent:
229 * blending disabled, an opaque constant fill, or a palette draw whose LUT maps every index to an
230 * opaque pixel - all under the fast blend pair, where an opaque source is a plain copy. Everything
231 * drawn before such a command inside its cover rectangle is overwritten, so a tile it fully covers
232 * starts its command walk there and skips the framebuffer read-back (the reverse-painter cull in
233 * `ProcessTile`).
234 */
235 bool opaqueOverwrite;
236 /** @brief Inclusive screen-space pixel rectangle the command is guaranteed to overwrite (exact drawn extent, scissor applied; valid when @ref opaqueOverwrite) */
237 std::int32_t coverMinX, coverMinY, coverMaxX, coverMaxY;
238
239 /**
240 * @brief Inline snapshot of the effect's fragment-callback parameter block
241 *
242 * The device fills @ref DrawContext::fragmentShaderUserData with a pointer into its own
243 * caller-stack storage, which dies when the draw call returns; deferral outlives that, so
244 * @ref SubmitCommand copies the block here (it is trivially copyable). The repointing of
245 * @ref ctx.fragmentShaderUserData at this storage happens in @ref Flush() - not at submit -
246 * because the command arena may still reallocate (and move every live command) while
247 * submissions continue; nothing dereferences the pointer between submit and the flush fixup.
248 */
249 alignas(16) std::uint8_t userDataStorage[MaxFragmentShaderUserDataSize];
250
251 /**
252 * @brief Index of this command's @ref SwPaletteLut in the flush window's LUT pool, or `-1`
253 *
254 * An index rather than a pointer because the pool still grows while commands are being
255 * submitted; @ref Flush() resolves it into @ref DrawContext::paletteLut once the pool is final.
256 */
257 std::int32_t paletteLutIndex;
258
259 /**
260 * @brief Snapshot of a general (vertex-fed) draw's interleaved clip-space vertices
261 *
262 * @ref DrawContext::vertexData points into the device's per-draw scratch buffer, which is
263 * overwritten by the next draw; deferral outlives that, so @ref SubmitCommand copies the
264 * vertex floats here and @ref Flush() repoints @ref ctx.vertexData at it (mirrors
265 * @ref userDataStorage - the flush-time fixup survives arena reallocation). Heap capacity is
266 * retained across reuse of the command slot.
267 */
268 SmallVector<float, 0> vertexStorage;
269
270 /** @brief Submit-time precomputed vertices and derived state of a procedural quad command */
271 PreparedQuad prep;
272 };
273
274 /** @brief Spins up the worker pool and resets the queue (idempotent; called once at startup) */
275 void Initialize();
276
277 /** @brief Signals the workers to exit, joins them and releases resources */
278 void Shutdown();
279
280 /** @brief Returns `true` when the layer is initialized and accepting deferred commands */
281 bool IsActive();
282
283 /** @brief Records the current viewport, snapshotted into every command submitted afterwards */
284 void SetViewport(std::int32_t x, std::int32_t y, std::int32_t width, std::int32_t height);
285
286 /**
287 @brief Points the layer at a new destination surface, flushing the previous one first
288
289 Flushes any commands still queued for the old target when the target actually changes, then
290 reconfigures the tile grid for the new one (the bin table grows on demand to fit it). A surface
291 edge beyond @ref MaxSurfaceDimension disables the layer until a valid target is set again.
292 Passing an unchanged target is a no-op.
293
294 @param buffer Base of the tightly packed `width * height * 4` RGBA8 destination
295 @param width Destination width in pixels
296 @param height Destination height in pixels
297 @param isFboTarget `true` for a render-target texture (rows stored bottom-up), `false` for the screen
298 */
299 void SetTargetBuffer(std::uint8_t* buffer, std::int32_t width, std::int32_t height, bool isFboTarget = false);
300
301 /**
302 @brief Submits a draw call for deferred tile-based rendering
303
304 @returns `true` if the command was accepted (and will be drawn by @ref Flush()), `false` if the
305 caller should rasterize it immediately (layer inactive, no target, or buffer full)
306 */
307 bool SubmitCommand(const DrawContext& ctx, PrimitiveType type,
308 std::int32_t firstVertex, std::int32_t count);
309
310 /**
311 @brief Renders every queued command tile by tile, then clears the queue
312
313 Bins the commands into tiles, processes the tiles (multi-threaded when `WITH_THREADS` is set,
314 sequential otherwise) and copies the results back into the destination surface. Called before the
315 surface is read for presentation or a different render target is bound. Waits for all workers to
316 finish before returning.
317 */
318 void Flush();
319
320 /** @brief Drops all queued commands without rendering them (e.g. after a full-surface clear) */
321 void DiscardPending();
322
323 /** @brief Returns the number of commands currently queued */
324 std::int32_t GetPendingCommandCount();
325 }
326 }
327
328 #endif