Estella 0.113.0
A fast 2D and 3D game engine powered by WebAssembly and ECS
Loading...
Searching...
No Matches
DrawCommand.hpp
Go to the documentation of this file.
1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
3#pragma once
4
9#include "./RenderItem.hpp"
10#include "./BlendMode.hpp"
13
14#include <algorithm>
15#include <bit>
16#include <cstring>
17
18namespace esengine {
19
20static constexpr u32 MAX_CMD_TEXTURE_SLOTS = 8;
21
22static constexpr u16 CMD_STATE_SCISSOR = 0x01;
23static constexpr u16 CMD_STATE_STENCIL_WRITE = 0x02;
24static constexpr u16 CMD_STATE_UI_STENCIL = 0x20;
25static constexpr u16 CMD_STATE_STENCIL_INCREMENT = 0x40;
26static constexpr u16 CMD_STATE_STENCIL_DECREMENT = 0x80;
27static constexpr u16 CMD_STATE_STENCIL_ZERO = 0x100;
28static constexpr u16 CMD_STATE_STENCIL_TEST = 0x04;
29static constexpr u16 CMD_STATE_CUSTOM_DRAW = 0x08;
30// Tests the reference the other way: drawn only where the stencil does NOT match.
31// A separate flag rather than a sign on the ref, so a draw inside a mask and one
32// outside the same mask never merge — they are different pipelines.
33static constexpr u16 CMD_STATE_STENCIL_OUT = 0x10;
34
41inline GfxStencilMode stencilModeOf(u16 stateFlags) {
44 if (stateFlags & CMD_STATE_STENCIL_ZERO) return GfxStencilMode::Zero;
45 if (stateFlags & CMD_STATE_STENCIL_WRITE) return GfxStencilMode::Write;
46 if (stateFlags & CMD_STATE_STENCIL_TEST) {
49 }
51}
52
74
80inline const char* batchBreakCounter(BatchBreak r) {
81 switch (r) {
82 case BatchBreak::RunStart: return "batch.break.runStart";
83 case BatchBreak::Instanced: return "batch.break.instanced";
84 case BatchBreak::Shader: return "batch.break.shader";
85 case BatchBreak::Blend: return "batch.break.blend";
86 case BatchBreak::Layout: return "batch.break.layout";
87 case BatchBreak::Material: return "batch.break.material";
88 case BatchBreak::Depth: return "batch.break.depth";
89 case BatchBreak::Cull: return "batch.break.cull";
90 case BatchBreak::State: return "batch.break.state";
91 case BatchBreak::Scissor: return "batch.break.scissor";
92 case BatchBreak::Stencil: return "batch.break.stencil";
93 case BatchBreak::IndexGap: return "batch.break.indexGap";
94 case BatchBreak::TextureSlots: return "batch.break.textureSlots";
95 default: return "batch.break.none";
96 }
97}
98
101
105
112
113 // The material handle this draw resolved from (0 = none). Identity for sort + merge so
114 // distinct materials never coalesce, and the lookup key for per-material GPU state.
116 // Pipeline depth/cull state, resolved from the material (or defaults). depth_write stays
117 // on with the test off — the engine's 2D state — unless a material overrides it.
118 bool depth_test = false;
119 bool depth_write = true;
120 u8 cull = 0;
124
127
132
135 // Kept beside the sort key rather than unpacked from it: the bit layout is
136 // buildSortKey's business alone, and a second place that knows it is a second
137 // place to forget when it moves. `layer` is here for the same reason.
144
145 // > 0 selects an instanced draw: index_count indices drawn instance_count times,
146 // with per-instance attributes based at vertex_byte_offset (see LayoutId::ParticleInstance).
148 // Bytes one of those records occupies; 0 = the stream's own stride, which the
149 // merge would have to guess. Set by whoever wrote them.
151 // The instance records already sit in a GPU buffer (a compute kernel wrote them): bound whole in place of the
152 // stream's slice. Never merged; instance_count says how many to draw.
154
155 // Geometry on the GPU rather than in this frame's pool. Set together or not
156 // at all; index_offset/index_count then index INTO these. Sorting, material and
157 // depth state are unchanged — where vertices live is not what is drawn.
161
162 // A skinned draw's pose: where its bone matrices start in the frame's pool
163 // and how many there are. Zero count = the geometry is not deformed.
166
167 // A morphed draw's shapes: 1 + where its block sits in the frame's pool, so
168 // 0 means the geometry is in the shape it was authored in.
170
171 // The indirect light where this draw stands: 1 + where its block sits in the
172 // frame's pool, so 0 means no volume holds it and the frame's environment
173 // answers instead.
176 // Where this draw's instances start in the frame's probe texture. A merged
177 // run reads slot `probe_base + gl_InstanceID`, which is why the merge
178 // records every instance's probe in draw order rather than dropping it.
180
182
183 // Vertices owned by this command (from vertex_byte_offset). Needed so the merge pass
184 // can rewrite their texIndex when coalescing into a multi-texture batch.
186
187 // Texture is not in the key: draws differing only by texture then sort adjacent and
188 // coalesce into one multi-texture batch (up to 8, selected per-vertex in the shader).
189
190 // Layer, then order, then stage — the author's two promises outrank the physical
191 // grouping. Stage first would let an opaque draw in layer 5 precede a painter draw in
192 // layer 3: a sorting layer's whole meaning inverted, and an order's one level finer.
193
194 // Under both, the 3D order. A blended draw composites onto what is there, so its
195 // depth IS the result and outranks batching; an opaque one is order-independent, so
196 // material groups first and depth breaks ties. Interleaved orders cost early-z.
197
198 // [63:48] layer | [47:40] order | [39:38] stage, then 38 bits the stage decides:
199 // opaque [37:30] shader | [29:27] blend | [26:25] flags | [24:14] material | [13:0] depth (or [13:6] geometry | [5:0] depth)
200 // blended [37:18] depth | [17:10] shader | [9:7] blend | [6:5] flags | [4:0] material
201
202 // A SortingGroup owns [63:40] for its members; [37:30] then carries the member's own
203 // order. See withGroupOrder.
204
205 // Material pays for the order field, being the only one that can afford it: a
206 // batching HINT, not identity (canMergeWith compares in full), so a collision costs
207 // a merge and never a wrong draw.
208
209 // Stage now has exactly its four values and no spare. A fifth would land in `order`
210 // and reorder the frame silently, so it stops the build here instead.
211 static_assert(static_cast<u32>(RenderStage::Overlay) <= 3,
212 "RenderStage outgrew the sort key's 2-bit field — re-lay the key out");
213
214 // `geometry`, when nonzero, is a hash of the mesh an instanced opaque draw repeats. It takes the top bits of the opaque depth field, so draws
215 // of one mesh that share a material sort together and merge into one instanced draw rather than alternating with another mesh's by depth. A
216 // batching hint like the material: a collision costs a merge, never a wrong draw. Opaque draws are order-independent, so only the coarse
217 // front-to-back order inside a mesh's run is spent.
219 BlendMode blend, u16 stateFlags, f32 depth, u32 materialId = 0,
220 i32 order = 0, u32 geometry = 0) {
221 i32 normalizedLayer = std::clamp(layer + 32768, 0, 65535);
222 u64 layerKey = static_cast<u64>(normalizedLayer & 0xFFFF) << 48;
223
224 u64 stageKey = static_cast<u64>(stage) << 38;
225
226 // Order-preserving float mapping — monotonic over the FULL float range, so
227 // any real-world depth sorts. `depth` is CameraView::viewDepth, larger =
228 // nearer: blended back-to-front, opaque front-to-back for early-z.
229 const bool blended = stage == RenderStage::Transparent || stage == RenderStage::Overlay;
230 u32 orderedDepth = blended ? orderedFloatBits(depth) : ~orderedFloatBits(depth);
231
232 // Blended spends its bits on depth (20: sign, exponent, 11 mantissa — a step of
233 // ~0.004 around z=10) and leaves material 5; opaque keeps depth at 14 and material
234 // 11. One trade twice: depth is what the eye sees, material only what batches well.
235 if (blended) {
236 return layerKey | orderBits(order) | stageKey
237 | (static_cast<u64>(orderedDepth >> 12) << 18)
238 | (static_cast<u64>(shaderId & 0xFF) << 10)
239 | (blendBits(blend) << 7)
240 | (static_cast<u64>(stateFlags & 0x03) << 5)
241 | (static_cast<u64>(materialId) & 0x1F);
242 }
243 const u64 depthField = geometry != 0
244 ? (static_cast<u64>(geometry & 0xFF) << 6) | static_cast<u64>(orderedDepth >> 26)
245 : static_cast<u64>(orderedDepth >> 18);
246 return layerKey | orderBits(order) | stageKey
247 | (static_cast<u64>(shaderId & 0xFF) << 30)
248 | (blendBits(blend) << 27)
249 | (static_cast<u64>(stateFlags & 0x03) << 25)
250 | ((static_cast<u64>(materialId) & 0x7FF) << 14)
251 | depthField;
252 }
253
258 static u64 blendBits(BlendMode blend) {
259 return static_cast<u64>(blend) & 0x7;
260 }
261
266 static u64 orderBits(i32 order) {
267 return static_cast<u64>(std::clamp(order + 128, 0, 255)) << 40;
268 }
269
278 static u64 withGroupOrder(u64 key, i32 memberOrder) {
279 constexpr u64 field = 0xFFull << 30;
280 return (key & ~field) | (static_cast<u64>(std::clamp(memberOrder + 128, 0, 255)) << 30);
281 }
282
283 // Order-preserving float → u32: flip the sign bit for positives, all bits for
284 // negatives, so unsigned compare matches float compare (finite values).
286 u32 bits = std::bit_cast<u32>(v);
287 return (bits & 0x80000000u) ? ~bits : (bits | 0x80000000u);
288 }
289
290 // Y-sorted variant (top-down occlusion): higher Y (further "back" under Y-up) draws
291 // first, so lower-on-screen entities land on top. Material and depth leave the key;
292 // shader/blend/flags stay as tie-breaks so equal-Y draws group for the merge.
293
294 // Same top three fields as buildSortKey, so a y-sorted layer and a plain one order
295 // correctly against each other; below them this spends its bits on worldY instead.
296
297 // Order outranks worldY because y-sort INFERS an order from position and an author
298 // stating one is overriding that inference. Without it a y-sorted layer has no
299 // override at all: z never reaches this key, so a shadow cannot be pinned under its owner.
300
301 // [63:48] layer | [47:40] order | [39:38] stage | [37:14] worldY
302 // [13:6] shader | [5:3] blend | [2:1] flags
304 u32 shaderId, BlendMode blend, u16 stateFlags,
305 i32 order = 0) {
306 i32 normalizedLayer = std::clamp(layer + 32768, 0, 65535);
307 u64 layerKey = static_cast<u64>(normalizedLayer & 0xFFFF) << 48;
308
309 u64 stageKey = static_cast<u64>(stage) << 38;
310
311 u32 yDescending = (~orderedFloatBits(worldY)) >> 8; // 24 bits, larger Y → smaller key
312 u64 yKey = static_cast<u64>(yDescending & 0xFFFFFF) << 14;
313
314 u64 shaderKey = static_cast<u64>(shaderId & 0xFF) << 6;
315 u64 blendKey = blendBits(blend) << 3;
316 u64 flagsKey = static_cast<u64>(stateFlags & 0x03) << 1;
317
318 return stageKey | layerKey | orderBits(order) | yKey | shaderKey | blendKey | flagsKey;
319 }
320
321 // Tree-ordered variant: the entity's place in the hierarchy walk takes the field worldY has in a y-sorted layer, so draws of every kind
322 // stack as their nodes do, and shader/blend/flags only separate what shares a node.
324 u32 shaderId, BlendMode blend, u16 stateFlags,
325 i32 order = 0) {
326 i32 normalizedLayer = std::clamp(layer + 32768, 0, 65535);
327 u64 layerKey = static_cast<u64>(normalizedLayer & 0xFFFF) << 48;
328
329 u64 stageKey = static_cast<u64>(stage) << 38;
330 u64 sequenceKey = static_cast<u64>(sequence & 0xFFFFFF) << 14;
331
332 u64 shaderKey = static_cast<u64>(shaderId & 0xFF) << 6;
333 u64 blendKey = blendBits(blend) << 3;
334 u64 flagsKey = static_cast<u64>(stateFlags & 0x03) << 1;
335
336 return stageKey | layerKey | orderBits(order) | sequenceKey | shaderKey | blendKey | flagsKey;
337 }
338
354 u8 textureSlotBudget(u8 reservedSlots) const {
355 if (material_id != 0) return 1;
356 return static_cast<u8>(MAX_CMD_TEXTURE_SLOTS - reservedSlots);
357 }
358
360 for (u8 i = 0; i < texture_count; ++i) {
361 if (texture_ids[i] == texId) return static_cast<i32>(i);
362 }
363 if (texture_count >= limit) return -1;
364 texture_ids[texture_count] = texId;
365 return static_cast<i32>(texture_count++);
366 }
367
381 bool orderIndependent() const {
383 }
384
391 bool sameInstancedGeometry(const DrawCommand& next) const {
392 if (!hasPersistentGeometry() || !next.hasPersistentGeometry()) return false;
393 if (instance_stride == 0 || instance_stride != next.instance_stride) return false;
394 if (skin_count != 0 || next.skin_count != 0) return false;
395 if (planar_index != next.planar_index) return false;
396 // Same reason: one draw can only be in one shape.
397 if (morph_index != 0 || next.morph_index != 0) return false;
398 // Indirect light is NOT in this list: it is per instance, so two draws
399 // standing in different places are one geometry drawn twice.
400
401 // BOTH, not just this one: an opaque head asked about a draw whose
402 // result depends on when it happens would otherwise swallow it and
403 // paint it with the head's own state.
404 if (!orderIndependent() || !next.orderIndependent()) return false;
405 if (vertex_buffer != next.vertex_buffer || index_buffer != next.index_buffer) return false;
406 if (vertex_layout != next.vertex_layout) return false;
407 // The same range of the same buffer: a draw is one instance of THIS.
408 if (index_offset != next.index_offset || index_count != next.index_count) return false;
409 // Textures are per draw here, not selected per vertex the way the Batch
410 // stream selects them, so instances sharing one draw share its samplers.
411 if (texture_count != next.texture_count) return false;
412 for (u8 s = 0; s < texture_count; ++s) {
413 if (texture_ids[s] != next.texture_ids[s]) return false;
414 }
415 return true;
416 }
417
420 // UI mask vertices are replayed to restore their parent's stencil.
421 // Changing sampler indices while merging the entering draw would also
422 // change its later replay, so both must keep the same binding plan.
425 if (texture_count != next.texture_count
426 || !std::equal(texture_ids, texture_ids + texture_count, next.texture_ids)) {
428 }
429 }
430 // An instanced draw is one command per emitter, except where a second
431 // command is the same geometry again — see sameInstancedGeometry, which
432 // the merge answers by relocating the records rather than by a draw.
433 if (instance_count != 0 || next.instance_count != 0) {
434 // A run carrying irradiance is bounded by what one block holds; one
435 // standing in no volume carries none and is not bounded.
436 if ((probe_index != 0 || next.probe_index != 0)
439 }
442 if (material_id != next.material_id) return BatchBreak::Material;
443 if (cull != next.cull) return BatchBreak::Cull;
444 if (depth_bias != next.depth_bias) return BatchBreak::Cull;
445 if (topology != next.topology) return BatchBreak::Layout;
446 if (state_flags != next.state_flags) return BatchBreak::State;
448 if (scissor != next.scissor) return BatchBreak::Scissor;
449 }
451 if (stencil_ref != next.stencil_ref) return BatchBreak::Stencil;
452 }
453 return BatchBreak::None;
454 }
456 if (blend_mode != next.blend_mode) return BatchBreak::Blend;
457 if (layout_id != next.layout_id || vertex_buffer != next.vertex_buffer
459 // Same material handle => same uniforms/textures; different ones must not
460 // coalesce. material_id 0 (no material) shares the path's defaults, so they still merge.
461 if (material_id != next.material_id) return BatchBreak::Material;
462 // Depth state is checked on its own rather than trusted to follow from the
463 // material. It used to: every draw resolved its depth from a material, so equal
464 // material_id implied equal state, and material_id 0 meant one shared set of
465 // defaults. Once a layer derives depth from the stage instead, two material-0
466 // draws in the same layer can differ — one opaque and writing depth, one blended
467 // and not — and merging them would silently give one of them the other's state.
468 // The symptom would be a blended sprite occasionally clipping what is behind it,
469 // depending on whether the two happened to land adjacent. Compared here as render
470 // state, not as stage: the stage is the reason, these three are the effect.
471 if (depth_test != next.depth_test) return BatchBreak::Depth;
472 if (depth_write != next.depth_write) return BatchBreak::Depth;
473 if (cull != next.cull) return BatchBreak::Cull;
474 if (depth_bias != next.depth_bias) return BatchBreak::Cull;
475 if (topology != next.topology) return BatchBreak::Layout;
476 if (state_flags != next.state_flags) return BatchBreak::State;
478 if (scissor != next.scissor) return BatchBreak::Scissor;
479 }
481 if (stencil_ref != next.stencil_ref) return BatchBreak::Stencil;
482 }
483 // Texture compatibility is decided by the merge (the combined set must fit in 8
484 // slots), not here, so different-texture draws can coalesce.
486 return BatchBreak::None;
487 }
488
489 bool canMergeWith(const DrawCommand& next) const {
490 if (planar_index != next.planar_index) return false;
491 return mergeBlocker(next) == BatchBreak::None;
492 }
493};
494
495} // namespace esengine
Blend mode enumeration for custom rendering.
Immutable GPU pipeline state — the backend-agnostic unit of "how to draw".
The indirect light where ONE draw stands, when a grid was baked for it.
Core type definitions and utilities for ESEngine.
GPU shader program for rendering.
Definition Shader.hpp:86
GfxStencilMode stencilModeOf(u16 stateFlags)
The stencil mode a draw's state flags mean.
static constexpr u16 CMD_STATE_UI_STENCIL
std::int32_t i32
Signed 32-bit integer.
Definition Types.hpp:54
static constexpr u16 CMD_STATE_STENCIL_DECREMENT
std::uint64_t u64
Unsigned 64-bit integer.
Definition Types.hpp:47
GfxStencilMode
Stencil behaviour baked into a pipeline. The reference value is dynamic (GfxDevice::setStencilReferen...
@ Test
Draw only INSIDE the mask: func Equal, op Keep.
@ Write
Write the reference where drawn (mask fill): func Always, op Replace, color write off.
@ Decrement
Restore the parent reference on leaving a nested mask.
@ Increment
Enter a nested mask only where the parent reference matches.
@ TestOutside
Draw only OUTSIDE it: func NotEqual, op Keep — a hole, not a window.
@ Off
No stencil test; full color write.
@ Zero
Retire a root mask without writing color.
static constexpr u16 CMD_STATE_STENCIL_INCREMENT
constexpr Entity INVALID_ENTITY
Invalid entity sentinel value.
Definition Types.hpp:174
std::int16_t i16
Signed 16-bit integer.
Definition Types.hpp:52
static constexpr u16 CMD_STATE_STENCIL_ZERO
static constexpr u16 CMD_STATE_SCISSOR
constexpr u32 PROBE_MAX_INSTANCES
How many instances of one merged draw carry their own irradiance.
std::uint32_t u32
Unsigned 32-bit integer.
Definition Types.hpp:45
BlendMode
Predefined blend modes for rendering.
Definition BlendMode.hpp:22
static constexpr u16 CMD_STATE_STENCIL_OUT
std::uint8_t u8
Unsigned 8-bit integer.
Definition Types.hpp:41
static constexpr u16 CMD_STATE_STENCIL_WRITE
std::uint16_t u16
Unsigned 16-bit integer.
Definition Types.hpp:43
LayoutId
Identifies a transient vertex stream / vertex format. Each layout has its own VBO+EBO+VAO in Transien...
Definition GfxEnums.hpp:88
const char * batchBreakCounter(BatchBreak r)
static constexpr u16 CMD_STATE_CUSTOM_DRAW
static constexpr u32 MAX_CMD_TEXTURE_SLOTS
static constexpr u16 CMD_STATE_STENCIL_TEST
GfxTopology
How a pipeline's indices assemble into primitives. Baked into the pipeline, as WebGPU bakes it,...
@ Triangles
Every three indices a triangle: all geometry the engine draws.
float f32
32-bit floating point
Definition Types.hpp:59
static u64 buildSortKey(RenderStage stage, i32 layer, u32 shaderId, BlendMode blend, u16 stateFlags, f32 depth, u32 materialId=0, i32 order=0, u32 geometry=0)
i32 addTextureSlot(u32 texId, u8 limit=MAX_CMD_TEXTURE_SLOTS)
BufferHandle instance_buffer
BatchBreak mergeBlocker(const DrawCommand &next) const
static u64 buildSortKeyTree(RenderStage stage, i32 layer, u32 sequence, u32 shaderId, BlendMode blend, u16 stateFlags, i32 order=0)
bool sameInstancedGeometry(const DrawCommand &next) const
bool hasPersistentGeometry() const
static u64 withGroupOrder(u64 key, i32 memberOrder)
Re-stamps a member's own order into a key whose top fields a SortingGroup has taken over.
i16 depth_bias
Depth-buffer units toward the eye.
bool canMergeWith(const DrawCommand &next) const
static u32 orderedFloatBits(f32 v)
static u64 blendBits(BlendMode blend)
The blend field, 3 bits wide wherever it appears.
bool orderIndependent() const
VertexLayoutHandle vertex_layout
BatchBreak break_reason
Why this draw call started.
static u64 orderBits(i32 order)
The order field at [47:40], biased so a negative order sorts below zero.
u32 texture_ids[MAX_CMD_TEXTURE_SLOTS]
u8 textureSlotBudget(u8 reservedSlots) const
Finds texId in this command's texture set, adds it (returns its slot), or -1 if the set is full....
static u64 buildSortKeyYSorted(RenderStage stage, i32 layer, f32 worldY, u32 shaderId, BlendMode blend, u16 stateFlags, i32 order=0)
BufferHandle index_buffer
GfxTopology topology
Triangles or lines.
u8 cull
CullMode: 0 = none, 1 = back, 2 = front.
BufferHandle vertex_buffer
Entity identifier with packed index + generation.
Definition Types.hpp:135