A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
feat(render): a sprite states where it sits inside its sorting layer
yhh7c674fd35e74
diff --git a/desktop b/desktopindex 9c17c5f76..2c9c04854 160000--- a/desktop+++ b/desktop@@ -1 +1 @@-Subproject commit 9c17c5f7625a54360e2058cd2a42379a18254f17+Subproject commit 2c9c04854c1a6cc65a4b5d044b7b1f4e1c3d092bdiff --git a/docs/astro/src/data/components.generated.json b/docs/astro/src/data/components.generated.jsonindex e07b31356..c94df2345 100644--- a/docs/astro/src/data/components.generated.json+++ b/docs/astro/src/data/components.generated.json@@ -3895,6 +3895,13 @@"doc": "Sorting layer — controls draw order across sprites.","range": "step 1"},+ {+ "key": "order",+ "type": "number",+ "default": "0",+ "doc": "Draw order inside the sorting layer — higher draws on top. Overrides the layer's Y-sort or depth ordering; leave 0 to keep it.",+ "range": "-128–127, step 1"+ },{"key": "lit","type": "boolean",diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.mdindex 0d3ba5e20..fcf00a5d2 100644--- a/sdk/etc/index.api.md+++ b/sdk/etc/index.api.md@@ -5,7 +5,7 @@ Symbols: 113 public · 92 beta · 1676 experimental · 3 deprecated## ABI_LAYOUT_HASH — const @experimental```-"840383cc170f0e8f"+"ffa08b49cfb9df43"```## ANCHOR_AXES — const @experimental@@ -3010,6 +3010,7 @@ width: number```layer: numberorder: LayerOrder+orderInLayer: numberworldY: numberworldZ: number```@@ -8228,6 +8229,7 @@ flipY: booleanlayer: numberlit: booleanmaterial: number+order: number | undefinedparallax: Vec2pivot: Vec2size: Vec2diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.mdindex 745734d8f..d1d401bfc 100644--- a/sdk/etc/index.native.api.md+++ b/sdk/etc/index.native.api.md@@ -5,7 +5,7 @@ Symbols: 113 public · 97 beta · 1695 experimental · 3 deprecated## ABI_LAYOUT_HASH — const @experimental```-"840383cc170f0e8f"+"ffa08b49cfb9df43"```## ANCHOR_AXES — const @experimental@@ -3018,6 +3018,7 @@ width: number```layer: numberorder: LayerOrder+orderInLayer: numberworldY: numberworldZ: number```@@ -8421,6 +8422,7 @@ flipY: booleanlayer: numberlit: booleanmaterial: number+order: number | undefinedparallax: Vec2pivot: Vec2size: Vec2diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.mdindex 2696119a1..bc736d74d 100644--- a/sdk/etc/index.node.api.md+++ b/sdk/etc/index.node.api.md@@ -3005,6 +3005,7 @@ width: number```layer: numberorder: LayerOrder+orderInLayer: numberworldY: numberworldZ: number```@@ -8223,6 +8224,7 @@ flipY: booleanlayer: numberlit: booleanmaterial: number+order: number | undefinedparallax: Vec2pivot: Vec2size: Vec2diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.mdindex 2974816c8..c71f8e296 100644--- a/sdk/etc/minigame.api.md+++ b/sdk/etc/minigame.api.md@@ -3005,6 +3005,7 @@ width: number```layer: numberorder: LayerOrder+orderInLayer: numberworldY: numberworldZ: number```@@ -8469,6 +8470,7 @@ flipY: booleanlayer: numberlit: booleanmaterial: number+order: number | undefinedparallax: Vec2pivot: Vec2size: Vec2diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.mdindex 264f43a75..88f1b3117 100644--- a/sdk/etc/wechat.api.md+++ b/sdk/etc/wechat.api.md@@ -3005,6 +3005,7 @@ width: number```layer: numberorder: LayerOrder+orderInLayer: numberworldY: numberworldZ: number```@@ -8230,6 +8231,7 @@ flipY: booleanlayer: numberlit: booleanmaterial: number+order: number | undefinedparallax: Vec2pivot: Vec2size: Vec2diff --git a/sdk/src/ecs/bridge/ptrAccessors.generated.ts b/sdk/src/ecs/bridge/ptrAccessors.generated.tsindex d8959eaa5..560925efd 100644--- a/sdk/src/ecs/bridge/ptrAccessors.generated.ts+++ b/sdk/src/ecs/bridge/ptrAccessors.generated.ts@@ -1617,6 +1617,7 @@ export interface SpritePtrData {uvOffset: Vec2;uvScale: Vec2;layer: number;+ order: number;lit: boolean;flipX: boolean;flipY: boolean;@@ -1638,14 +1639,15 @@ export function fillSprite(const uvOffset_ = out.uvOffset; uvOffset_.x = f32[(ptr + 36) >> 2]; uvOffset_.y = f32[((ptr + 36) >> 2) + 1];const uvScale_ = out.uvScale; uvScale_.x = f32[(ptr + 44) >> 2]; uvScale_.y = f32[((ptr + 44) >> 2) + 1];out.layer = u32[(ptr + 52) >> 2] | 0;- out.lit = u8[ptr + 56] !== 0;- out.flipX = u8[ptr + 57] !== 0;- out.flipY = u8[ptr + 58] !== 0;- const tileSize_ = out.tileSize; tileSize_.x = f32[(ptr + 60) >> 2]; tileSize_.y = f32[((ptr + 60) >> 2) + 1];- const tileSpacing_ = out.tileSpacing; tileSpacing_.x = f32[(ptr + 68) >> 2]; tileSpacing_.y = f32[((ptr + 68) >> 2) + 1];- const parallax_ = out.parallax; parallax_.x = f32[(ptr + 76) >> 2]; parallax_.y = f32[((ptr + 76) >> 2) + 1];- out.material = u32[(ptr + 84) >> 2];- out.enabled = u8[ptr + 88] !== 0;+ out.order = u32[(ptr + 56) >> 2] | 0;+ out.lit = u8[ptr + 60] !== 0;+ out.flipX = u8[ptr + 61] !== 0;+ out.flipY = u8[ptr + 62] !== 0;+ const tileSize_ = out.tileSize; tileSize_.x = f32[(ptr + 64) >> 2]; tileSize_.y = f32[((ptr + 64) >> 2) + 1];+ const tileSpacing_ = out.tileSpacing; tileSpacing_.x = f32[(ptr + 72) >> 2]; tileSpacing_.y = f32[((ptr + 72) >> 2) + 1];+ const parallax_ = out.parallax; parallax_.x = f32[(ptr + 80) >> 2]; parallax_.y = f32[((ptr + 80) >> 2) + 1];+ out.material = u32[(ptr + 88) >> 2];+ out.enabled = u8[ptr + 92] !== 0;}export function writeSprite(@@ -1659,14 +1661,15 @@ export function writeSprite(f32[(ptr + 36) >> 2] = data.uvOffset.x; f32[((ptr + 36) >> 2) + 1] = data.uvOffset.y;f32[(ptr + 44) >> 2] = data.uvScale.x; f32[((ptr + 44) >> 2) + 1] = data.uvScale.y;u32[(ptr + 52) >> 2] = data.layer | 0;- u8[ptr + 56] = data.lit ? 1 : 0;- u8[ptr + 57] = data.flipX ? 1 : 0;- u8[ptr + 58] = data.flipY ? 1 : 0;- f32[(ptr + 60) >> 2] = data.tileSize.x; f32[((ptr + 60) >> 2) + 1] = data.tileSize.y;- f32[(ptr + 68) >> 2] = data.tileSpacing.x; f32[((ptr + 68) >> 2) + 1] = data.tileSpacing.y;- f32[(ptr + 76) >> 2] = data.parallax.x; f32[((ptr + 76) >> 2) + 1] = data.parallax.y;- u32[(ptr + 84) >> 2] = data.material;- u8[ptr + 88] = data.enabled ? 1 : 0;+ u32[(ptr + 56) >> 2] = data.order | 0;+ u8[ptr + 60] = data.lit ? 1 : 0;+ u8[ptr + 61] = data.flipX ? 1 : 0;+ u8[ptr + 62] = data.flipY ? 1 : 0;+ f32[(ptr + 64) >> 2] = data.tileSize.x; f32[((ptr + 64) >> 2) + 1] = data.tileSize.y;+ f32[(ptr + 72) >> 2] = data.tileSpacing.x; f32[((ptr + 72) >> 2) + 1] = data.tileSpacing.y;+ f32[(ptr + 80) >> 2] = data.parallax.x; f32[((ptr + 80) >> 2) + 1] = data.parallax.y;+ u32[(ptr + 88) >> 2] = data.material;+ u8[ptr + 92] = data.enabled ? 1 : 0;}export function createSpriteData(): SpritePtrData {@@ -1678,6 +1681,7 @@ export function createSpriteData(): SpritePtrData {uvOffset: { x: 0, y: 0 },uvScale: { x: 0, y: 0 },layer: 0,+ order: 0,lit: false,flipX: false,flipY: false,diff --git a/sdk/src/ecs/component.generated.ts b/sdk/src/ecs/component.generated.tsindex 557cdda9a..c8cfa3364 100644--- a/sdk/src/ecs/component.generated.ts+++ b/sdk/src/ecs/component.generated.ts@@ -15,7 +15,7 @@ import type { AlignContent, AlignItems, AlignSelf, BodyType, CanvasScaleMode, Cl* getAbiLayoutHash(); BuiltinBridge.connect() compares them and refuses to* run on mismatch, because mismatched offsets read the wrong heap bytes.*/-export const ABI_LAYOUT_HASH = '840383cc170f0e8f';+export const ABI_LAYOUT_HASH = 'ffa08b49cfb9df43';/*** One asset-valued field of a component: which field, and what kind of@@ -851,6 +851,7 @@ export const COMPONENT_META: Record<string, ComponentMetaEntry> = {uvOffset: { x: 0, y: 0 },uvScale: { x: 1, y: 1 },layer: 0,+ order: 0,lit: false,flipX: false,flipY: false,@@ -874,6 +875,7 @@ export const COMPONENT_META: Record<string, ComponentMetaEntry> = {uvOffset: { advanced: true },uvScale: { advanced: true },layer: { step: 1, tooltip: "Sorting layer — controls draw order across sprites.", enumSource: "sortingLayers" },+ order: { min: -128, max: 127, step: 1, tooltip: "Draw order inside the sorting layer — higher draws on top. Overrides the layer's Y-sort or depth ordering; leave 0 to keep it." },lit: { tooltip: "Receive 2D lights: Light entities light this sprite (flat normal). A custom material overrides this." },tileSize: { advanced: true },tileSpacing: { advanced: true },@@ -1510,6 +1512,7 @@ export interface SpriteData {uvOffset: Vec2;uvScale: Vec2;layer: number;+ order?: number;lit: boolean;flipX: boolean;flipY: boolean;diff --git a/sdk/src/ecs/entityPick.ts b/sdk/src/ecs/entityPick.tsindex c9cb34f8e..fc5e34b76 100644--- a/sdk/src/ecs/entityPick.ts+++ b/sdk/src/ecs/entityPick.ts@@ -70,7 +70,8 @@ export function pickEntitiesByRay(const box = meshWorldBox(world, entity) ?? entityWorldBox(world, entity, { iconHalf });if (!box || entityBoxRayHit(box, ray.origin, ray.dir) === null) continue;- const layer = world.has(entity, Sprite) ? world.get(entity, Sprite).layer : unlayered;+ const sprite = world.has(entity, Sprite) ? world.get(entity, Sprite) : null;+ const layer = sprite ? sprite.layer : unlayered;const t = world.get(entity, Transform);hits.push({entity,@@ -78,6 +79,7 @@ export function pickEntitiesByRay(rank: {layer,order: layerOrderOf(layer, opts.ySortLayers ?? 0, opts.depthLayers ?? 0),+ orderInLayer: sprite?.order ?? 0,worldY: t.worldPosition.y,worldZ: t.worldPosition.z ?? 0,},diff --git a/sdk/src/render/layerOrder.ts b/sdk/src/render/layerOrder.tsindex 7a954aceb..6fd258266 100644--- a/sdk/src/render/layerOrder.ts+++ b/sdk/src/render/layerOrder.ts@@ -51,11 +51,25 @@ export function layerFrontness(order: LayerOrder, worldY: number, worldZ: numberreturn order === LayerOrder.YSort ? -worldY : worldZ;}-/** What a draw's place in the frame depends on: its layer, that layer's rule, and- * the two world coordinates either rule can be about. */+/**+ * The range the engine's sort key gives an order, which this mirror has to share:+ * ranking 200 above 300 here while the frame drew both clamped to 127 would pick+ * the sprite underneath. See `DrawCommand::orderBits`.+ */+export function clampDrawOrder(order: number): number {+ return Math.max(-128, Math.min(127, Math.trunc(order) || 0));+}++/** What a draw's place in the frame depends on: its layer, where it sits inside+ * that layer, the layer's rule, and the two world coordinates either rule uses. */export interface DrawRank {layer: number;+ /** The layer's RULE — how it resolves its contents. Not to be confused with+ * `orderInLayer`, which is one draw's stated place inside it. */order: LayerOrder;+ /** `Sprite.order`: the author's explicit place within the layer, outranking+ * whatever the rule would have inferred. 0 means nothing was stated. */+ orderInLayer: number;worldY: number;worldZ: number;}@@ -75,6 +89,12 @@ export interface DrawRank {export function compareDrawRank(a: DrawRank, b: DrawRank): number {if (a.order === LayerOrder.Depth && b.order === LayerOrder.Depth) return a.worldZ - b.worldZ;if (a.layer !== b.layer) return a.layer - b.layer;+ // Below the layer and above the rule, exactly where the sort key puts it: a+ // stated order is the author overriding what the rule would infer, and the pick+ // has to agree or it selects the sprite that lost.+ const ao = clampDrawOrder(a.orderInLayer);+ const bo = clampDrawOrder(b.orderInLayer);+ if (ao !== bo) return ao - bo;return layerFrontness(a.order, a.worldY, a.worldZ) - layerFrontness(b.order, b.worldY, b.worldZ);}diff --git a/sdk/src/wasm/ptrLayouts.generated.ts b/sdk/src/wasm/ptrLayouts.generated.tsindex 7c461f251..19ecb1216 100644--- a/sdk/src/wasm/ptrLayouts.generated.ts+++ b/sdk/src/wasm/ptrLayouts.generated.ts@@ -437,14 +437,15 @@ export const PTR_LAYOUTS: Record<string, PtrLayout> = {{ name: 'uvOffset', type: 'vec2', offset: 36 },{ name: 'uvScale', type: 'vec2', offset: 44 },{ name: 'layer', type: 'i32', offset: 52 },- { name: 'lit', type: 'bool', offset: 56 },- { name: 'flipX', type: 'bool', offset: 57 },- { name: 'flipY', type: 'bool', offset: 58 },- { name: 'tileSize', type: 'vec2', offset: 60 },- { name: 'tileSpacing', type: 'vec2', offset: 68 },- { name: 'parallax', type: 'vec2', offset: 76 },- { name: 'material', type: 'u32', offset: 84 },- { name: 'enabled', type: 'bool', offset: 88 },+ { name: 'order', type: 'i32', offset: 56 },+ { name: 'lit', type: 'bool', offset: 60 },+ { name: 'flipX', type: 'bool', offset: 61 },+ { name: 'flipY', type: 'bool', offset: 62 },+ { name: 'tileSize', type: 'vec2', offset: 64 },+ { name: 'tileSpacing', type: 'vec2', offset: 72 },+ { name: 'parallax', type: 'vec2', offset: 80 },+ { name: 'material', type: 'u32', offset: 88 },+ { name: 'enabled', type: 'bool', offset: 92 },],},TilemapLayer: {diff --git a/sdk/src/wasm/wasm.generated.ts b/sdk/src/wasm/wasm.generated.tsindex 719d095d0..6126642a8 100644--- a/sdk/src/wasm/wasm.generated.ts+++ b/sdk/src/wasm/wasm.generated.ts@@ -728,6 +728,7 @@ export interface Sprite {uvOffset: Vec2;uvScale: Vec2;layer: number;+ order: number;lit: boolean;flipX: boolean;flipY: boolean;diff --git a/sdk/tests/__snapshots__/component-fieldmeta-golden.test.ts.snap b/sdk/tests/__snapshots__/component-fieldmeta-golden.test.ts.snapindex 41262a34a..453220f7c 100644--- a/sdk/tests/__snapshots__/component-fieldmeta-golden.test.ts.snap+++ b/sdk/tests/__snapshots__/component-fieldmeta-golden.test.ts.snap@@ -936,6 +936,12 @@ exports[`builtin FieldMeta (RC9-1 equivalence gate) > matches the golden snapsho"material": {"advanced": true,},+ "order": {+ "max": 127,+ "min": -128,+ "step": 1,+ "tooltip": "Draw order inside the sorting layer — higher draws on top. Overrides the layer's Y-sort or depth ordering; leave 0 to keep it.",+ },"parallax": {"advanced": true,"tooltip": "Parallax scroll factor (1 = with world, <1 = slower, 0 = locked to camera).",diff --git a/sdk/tests/layer-order.test.ts b/sdk/tests/layer-order.test.tsindex b0f2128b6..24e9ddd8d 100644--- a/sdk/tests/layer-order.test.ts+++ b/sdk/tests/layer-order.test.ts@@ -55,8 +55,8 @@ describe('layerFrontness', () => {});describe('compareDrawRank', () => {- const rank = (layer: number, order: LayerOrder, worldZ = 0, worldY = 0) =>- ({ layer, order, worldY, worldZ });+ const rank = (layer: number, order: LayerOrder, worldZ = 0, worldY = 0, orderInLayer = 0) =>+ ({ layer, order, worldY, worldZ, orderInLayer });it('gives the higher sorting layer the front, as paint order does', () => {expect(compareDrawRank(rank(5, LayerOrder.Painter), rank(1, LayerOrder.Painter))).toBeGreaterThan(0);@@ -89,4 +89,36 @@ describe('compareDrawRank', () => {expect(Math.sign(compareDrawRank(a, b))).toBe(-Math.sign(compareDrawRank(b, a)));expect(compareDrawRank(a, a)).toBe(0);});++ // Each of these is a case the layer's own rule gets wrong on purpose, so what is+ // measured is Sprite.order overriding it — the thing the sort key does one field+ // below the layer. A pick that skipped this selects the sprite underneath.+ it('lets a stated order override the rule that would have decided', () => {+ // Painter: the farther sprite is told to sit on top.+ expect(compareDrawRank(rank(1, LayerOrder.Painter, -10, 0, 1),+ rank(1, LayerOrder.Painter, 10))).toBeGreaterThan(0);+ // Y-sort: the one further back is told to sit on top. This layer had no other+ // override at all — z never reaches a y-sorted key.+ expect(compareDrawRank(rank(1, LayerOrder.YSort, 0, 50, 1),+ rank(1, LayerOrder.YSort, 0, -50))).toBeGreaterThan(0);+ });++ it('leaves the rule in charge where no order was stated', () => {+ expect(compareDrawRank(rank(1, LayerOrder.YSort, 0, -50, 5),+ rank(1, LayerOrder.YSort, 0, 50, 5))).toBeGreaterThan(0);+ });++ it('keeps an order inside its own layer', () => {+ expect(compareDrawRank(rank(1, LayerOrder.Painter, 0, 0, 127),+ rank(2, LayerOrder.Painter, 0, 0, -128))).toBeLessThan(0);+ });++ // Biased and clamped like the engine's key: -1 sinks below an unstated 0, and two+ // orders past the range compare EQUAL because the frame drew them equal.+ it('mirrors the key’s sign and its clamp', () => {+ expect(compareDrawRank(rank(1, LayerOrder.Painter, 0, 0, -1),+ rank(1, LayerOrder.Painter))).toBeLessThan(0);+ expect(compareDrawRank(rank(1, LayerOrder.Painter, 0, 0, 200),+ rank(1, LayerOrder.Painter, 0, 0, 300))).toBe(0);+ });});diff --git a/src/esengine/bindings/EditorAPI.generated.cpp b/src/esengine/bindings/EditorAPI.generated.cppindex fd4bf0a87..a276e7290 100644--- a/src/esengine/bindings/EditorAPI.generated.cpp+++ b/src/esengine/bindings/EditorAPI.generated.cpp@@ -2,10 +2,10 @@* @file EditorAPI.generated.cpp* @brief Auto-generated editor API with string-dispatched component access* @details Generated by EHT - DO NOT EDIT- * @schema_hash b6a802e71e3a8026+ * @schema_hash 2847d9de83059b20*/-#define ES_EDITOR_API_SCHEMA_HASH "b6a802e71e3a8026"+#define ES_EDITOR_API_SCHEMA_HASH "2847d9de83059b20"#include <emscripten/bind.h>#include <string>@@ -553,6 +553,7 @@ std::string editor_getComponentSchema(const std::string& name) {{"key":"uvScale.x","type":"float","group":"Sprite"},{"key":"uvScale.y","type":"float","group":"Sprite"},{"key":"layer","type":"int","group":"Sprite"},+ {"key":"order","type":"int","group":"Sprite"},{"key":"lit","type":"bool","group":"Sprite"},{"key":"flipX","type":"bool","group":"Sprite"},{"key":"flipY","type":"bool","group":"Sprite"},@@ -2140,6 +2141,7 @@ bool editor_setInt(Registry& reg, u32 e, const std::string& comp, const std::strauto& c = reg.get<esengine::ecs::Sprite>(entity);if (field == "texture") { c.texture = resource::TextureHandle(static_cast<u32>(value)); }else if (field == "layer") { c.layer = static_cast<i32>(value); }+ else if (field == "order") { c.order = static_cast<i32>(value); }else if (field == "material") { c.material = static_cast<u32>(value); }else { return false; }return true;@@ -2340,6 +2342,7 @@ i32 editor_getInt(Registry& reg, u32 e, const std::string& comp, const std::striconst auto& c = reg.get<esengine::ecs::Sprite>(entity);if (field == "texture") { return static_cast<i32>(c.texture.id()); }else if (field == "layer") { return static_cast<i32>(c.layer); }+ else if (field == "order") { return static_cast<i32>(c.order); }else if (field == "material") { return static_cast<i32>(c.material); }} else if (comp == "TilemapLayer") {if (!reg.has<esengine::ecs::TilemapLayer>(entity)) return 0;diff --git a/src/esengine/bindings/WebBindings.generated.cpp b/src/esengine/bindings/WebBindings.generated.cppindex af1650b80..b5cca711f 100644--- a/src/esengine/bindings/WebBindings.generated.cpp+++ b/src/esengine/bindings/WebBindings.generated.cpp@@ -1022,6 +1022,7 @@ struct SpriteJS {glm::vec2 uvOffset;glm::vec2 uvScale;i32 layer;+ i32 order;bool lit;bool flipX;bool flipY;@@ -1040,6 +1041,7 @@ void spriteApplyJS(esengine::ecs::Sprite& c, const SpriteJS& js) {c.uvOffset = js.uvOffset;c.uvScale = js.uvScale;c.layer = js.layer;+ c.order = js.order;c.lit = js.lit;c.flipX = js.flipX;c.flipY = js.flipY;@@ -1065,6 +1067,7 @@ SpriteJS spriteToJS(const esengine::ecs::Sprite& c) {js.uvOffset = c.uvOffset;js.uvScale = c.uvScale;js.layer = c.layer;+ js.order = c.order;js.lit = c.lit;js.flipX = c.flipX;js.flipY = c.flipY;@@ -1739,6 +1742,7 @@ EMSCRIPTEN_BINDINGS(esengine_components) {.field("uvOffset", &SpriteJS::uvOffset).field("uvScale", &SpriteJS::uvScale).field("layer", &SpriteJS::layer)+ .field("order", &SpriteJS::order).field("lit", &SpriteJS::lit).field("flipX", &SpriteJS::flipX).field("flipY", &SpriteJS::flipY)@@ -3116,14 +3120,15 @@ static_assert(offsetof(esengine::ecs::Sprite, pivot) == 28, "ABI offset drift: estatic_assert(offsetof(esengine::ecs::Sprite, uvOffset) == 36, "ABI offset drift: esengine::ecs::Sprite.uvOffset (EHT expected 36)");static_assert(offsetof(esengine::ecs::Sprite, uvScale) == 44, "ABI offset drift: esengine::ecs::Sprite.uvScale (EHT expected 44)");static_assert(offsetof(esengine::ecs::Sprite, layer) == 52, "ABI offset drift: esengine::ecs::Sprite.layer (EHT expected 52)");-static_assert(offsetof(esengine::ecs::Sprite, lit) == 56, "ABI offset drift: esengine::ecs::Sprite.lit (EHT expected 56)");-static_assert(offsetof(esengine::ecs::Sprite, flipX) == 57, "ABI offset drift: esengine::ecs::Sprite.flipX (EHT expected 57)");-static_assert(offsetof(esengine::ecs::Sprite, flipY) == 58, "ABI offset drift: esengine::ecs::Sprite.flipY (EHT expected 58)");-static_assert(offsetof(esengine::ecs::Sprite, tileSize) == 60, "ABI offset drift: esengine::ecs::Sprite.tileSize (EHT expected 60)");-static_assert(offsetof(esengine::ecs::Sprite, tileSpacing) == 68, "ABI offset drift: esengine::ecs::Sprite.tileSpacing (EHT expected 68)");-static_assert(offsetof(esengine::ecs::Sprite, parallax) == 76, "ABI offset drift: esengine::ecs::Sprite.parallax (EHT expected 76)");-static_assert(offsetof(esengine::ecs::Sprite, material) == 84, "ABI offset drift: esengine::ecs::Sprite.material (EHT expected 84)");-static_assert(offsetof(esengine::ecs::Sprite, enabled) == 88, "ABI offset drift: esengine::ecs::Sprite.enabled (EHT expected 88)");+static_assert(offsetof(esengine::ecs::Sprite, order) == 56, "ABI offset drift: esengine::ecs::Sprite.order (EHT expected 56)");+static_assert(offsetof(esengine::ecs::Sprite, lit) == 60, "ABI offset drift: esengine::ecs::Sprite.lit (EHT expected 60)");+static_assert(offsetof(esengine::ecs::Sprite, flipX) == 61, "ABI offset drift: esengine::ecs::Sprite.flipX (EHT expected 61)");+static_assert(offsetof(esengine::ecs::Sprite, flipY) == 62, "ABI offset drift: esengine::ecs::Sprite.flipY (EHT expected 62)");+static_assert(offsetof(esengine::ecs::Sprite, tileSize) == 64, "ABI offset drift: esengine::ecs::Sprite.tileSize (EHT expected 64)");+static_assert(offsetof(esengine::ecs::Sprite, tileSpacing) == 72, "ABI offset drift: esengine::ecs::Sprite.tileSpacing (EHT expected 72)");+static_assert(offsetof(esengine::ecs::Sprite, parallax) == 80, "ABI offset drift: esengine::ecs::Sprite.parallax (EHT expected 80)");+static_assert(offsetof(esengine::ecs::Sprite, material) == 88, "ABI offset drift: esengine::ecs::Sprite.material (EHT expected 88)");+static_assert(offsetof(esengine::ecs::Sprite, enabled) == 92, "ABI offset drift: esengine::ecs::Sprite.enabled (EHT expected 92)");static_assert(offsetof(esengine::ecs::TilemapLayer, cellSize) == 0, "ABI offset drift: esengine::ecs::TilemapLayer.cellSize (EHT expected 0)");static_assert(offsetof(esengine::ecs::TilemapLayer, orientation) == 8, "ABI offset drift: esengine::ecs::TilemapLayer.orientation (EHT expected 8)");static_assert(offsetof(esengine::ecs::TilemapLayer, hexSideLength) == 12, "ABI offset drift: esengine::ecs::TilemapLayer.hexSideLength (EHT expected 12)");@@ -3213,7 +3218,7 @@ static_assert(offsetof(esengine::ecs::Velocity, angular) == 12, "ABI offset drif// ABI Hash -- runtime handshake against the SDK bundle// =============================================================================-static const char* kEsAbiLayoutHash = "840383cc170f0e8f";+static const char* kEsAbiLayoutHash = "ffa08b49cfb9df43";std::string esengineGetAbiLayoutHash() {return std::string(kEsAbiLayoutHash);diff --git a/src/esengine/ecs/components/Sprite.hpp b/src/esengine/ecs/components/Sprite.hppindex 1a33ec51b..a90e99425 100644--- a/src/esengine/ecs/components/Sprite.hpp+++ b/src/esengine/ecs/components/Sprite.hpp@@ -73,6 +73,12 @@ struct Sprite {ES_PROPERTY(step=1, enum_source=sortingLayers, tooltip="Sorting layer — controls draw order across sprites.")i32 layer{0};+ /** @brief Order WITHIN the sorting layer; higher draws on top. The explicit answer+ * that overrides whatever the layer infers — Y-sort, or depth from z — and+ * the only one a Y-sorted layer has. Range -128..127 (clamped). */+ ES_PROPERTY(step=1, min=-128, max=127, optional, tooltip="Draw order inside the sorting layer — higher draws on top. Overrides the layer's Y-sort or depth ordering; leave 0 to keep it.")+ i32 order{0};+/** @brief Lit by the scene's 2D lights (Light), no material needed. Off = unlit. */ES_PROPERTY(tooltip="Receive 2D lights: Light entities light this sprite (flat normal). A custom material overrides this.")bool lit{false};diff --git a/src/esengine/renderer/draw/BatchBuilder.cpp b/src/esengine/renderer/draw/BatchBuilder.cppindex e0bac7ff5..f26c507b8 100644--- a/src/esengine/renderer/draw/BatchBuilder.cpp+++ b/src/esengine/renderer/draw/BatchBuilder.cpp@@ -52,7 +52,7 @@ void pushBatchDraw(DrawList& drawList, const ClipState& clips,if (!drawList.layerVisible(key.cullBit ? key.cullBit : DrawList::layerBit(key.layer))) return;DrawCommand cmd{};- const auto order = drawList.layerOrder(key.layer);+ const auto resolve = drawList.layerOrder(key.layer);// A depth layer decides its own stage and depth state; every other layer takes// what the caller resolved from the material. The rule is the physical one, so@@ -65,7 +65,7 @@ void pushBatchDraw(DrawList& drawList, const ClipState& clips,RenderStage stage = key.stage;bool depthTest = key.depthTest;bool depthWrite = key.depthWrite;- if (order == DrawList::LayerOrder::Depth) {+ if (resolve == DrawList::LayerOrder::Depth) {const bool opaque = key.blend == BlendMode::None;stage = opaque ? RenderStage::Opaque : RenderStage::Transparent;depthTest = true;@@ -75,11 +75,11 @@ void pushBatchDraw(DrawList& drawList, const ClipState& clips,// stateFlags is 0: ClipState stamps the real scissor/stencil below, after the key// exists. A stencil write still precedes the draws testing it because UI pre-order// puts a mask below its descendants in LAYER, the key's top field. Not so on one layer.- cmd.sort_key = order == DrawList::LayerOrder::YSort+ cmd.sort_key = resolve == DrawList::LayerOrder::YSort? DrawCommand::buildSortKeyYSorted(stage, key.layer, key.y, key.shaderId,- key.blend, 0)+ key.blend, 0, key.order): DrawCommand::buildSortKey(stage, key.layer, key.shaderId,- key.blend, 0, key.depth, key.materialId);+ key.blend, 0, key.depth, key.materialId, key.order);cmd.stage = stage;cmd.index_offset = indexOffset;cmd.index_count = indexCount;diff --git a/src/esengine/renderer/draw/BatchBuilder.hpp b/src/esengine/renderer/draw/BatchBuilder.hppindex b88388f77..ece9ed9f3 100644--- a/src/esengine/renderer/draw/BatchBuilder.hpp+++ b/src/esengine/renderer/draw/BatchBuilder.hpp@@ -80,6 +80,10 @@ inline glm::vec3 rotatePoint(const glm::vec3& center, f32 px, f32 py, f32 cosA,struct BatchDrawKey {RenderStage stage = RenderStage::Transparent;i32 layer = 0;+ // Where this draw sits INSIDE its sorting layer; higher draws on top. Outranks depth+ // and y-sort alike, so it holds whatever ordering the layer was given. Clamped to+ // -128..127; 0 says nothing, leaving a renderable without such a field as it was.+ i32 order = 0;u32 shaderId = 0;BlendMode blend = BlendMode::Normal;u32 textureId = 0;diff --git a/src/esengine/renderer/draw/DrawCommand.hpp b/src/esengine/renderer/draw/DrawCommand.hppindex 4eaf4e24c..f6d4673a7 100644--- a/src/esengine/renderer/draw/DrawCommand.hpp+++ b/src/esengine/renderer/draw/DrawCommand.hpp@@ -132,30 +132,37 @@ struct DrawCommand {// can rewrite their texIndex when coalescing into a multi-texture batch.u32 vertex_count = 0;- // Texture is no longer part of the sort key: dropping it lets draws that differ only- // by texture sort adjacent and coalesce into one multi-texture batch (up to 8 textures,- // selected per-vertex in the shader). Order within a layer is otherwise unchanged.- // Below stage the field order depends on it: a blended draw composites onto what is- // already there, so its depth order IS the result and outranks batching, while an- // opaque draw is order-independent, so material groups first and depth breaks ties.- //- // Layer outranks stage, and that order is load-bearing. A sorting layer is a promise- // the user made about what draws on top of what; a stage is how one layer resolves- // its own contents. Ranking stage first — the classic 3D pipeline order, where every- // opaque draw precedes every transparent one — would let an opaque draw in layer 5- // jump ahead of a painter draw in layer 3, which is the sorting layer's entire- // meaning inverted. Within a layer the 3D order is the right one: opaque first- // (front-to-back, early-z), then blended (back-to-front).- //- // [63:48] layer | [47:44] stage, then 44 bits whose order the stage decides:- // opaque [43:36] shader | [35:33] blend | [32:31] flags | [30:14] material | [13:0] depth- // blended [43:24] depth | [23:16] shader | [15:13] blend | [12:11] flags | [10:0] material+ // Texture is not in the key: draws differing only by texture then sort adjacent and+ // coalesce into one multi-texture batch (up to 8, selected per-vertex in the shader).++ // Layer, then order, then stage — the author's two promises outrank the physical+ // grouping. Stage first would let an opaque draw in layer 5 precede a painter draw in+ // layer 3: a sorting layer's whole meaning inverted, and an order's one level finer.++ // Under both, the 3D order. A blended draw composites onto what is there, so its+ // depth IS the result and outranks batching; an opaque one is order-independent, so+ // material groups first and depth breaks ties. Interleaved orders cost early-z.++ // [63:48] layer | [47:40] order | [39:38] stage, then 38 bits the stage decides:+ // opaque [37:30] shader | [29:27] blend | [26:25] flags | [24:14] material | [13:0] depth+ // blended [37:18] depth | [17:10] shader | [9:7] blend | [6:5] flags | [4:0] material++ // Material pays for the order field, being the only one that can afford it: a+ // batching HINT, not identity (canMergeWith compares in full), so a collision costs+ // a merge and never a wrong draw.++ // Stage now has exactly its four values and no spare. A fifth would land in `order`+ // and reorder the frame silently, so it stops the build here instead.+ static_assert(static_cast<u32>(RenderStage::Overlay) <= 3,+ "RenderStage outgrew the sort key's 2-bit field — re-lay the key out");+static u64 buildSortKey(RenderStage stage, i32 layer, u32 shaderId,- BlendMode blend, u16 stateFlags, f32 depth, u32 materialId = 0) {+ BlendMode blend, u16 stateFlags, f32 depth, u32 materialId = 0,+ i32 order = 0) {i32 normalizedLayer = std::clamp(layer + 32768, 0, 65535);u64 layerKey = static_cast<u64>(normalizedLayer & 0xFFFF) << 48;- u64 stageKey = static_cast<u64>(stage) << 44;+ u64 stageKey = static_cast<u64>(stage) << 38;// Order-preserving float mapping — monotonic over the FULL float range, so// any real-world depth sorts. `depth` is CameraView::viewDepth, larger =@@ -164,24 +171,40 @@ struct DrawCommand {u32 orderedDepth = blended ? orderedFloatBits(depth) : ~orderedFloatBits(depth);// Blended spends its bits on depth (20: sign, exponent, 11 mantissa — a step of- // ~0.004 around z=10) and leaves material 11. Material here is a batching hint,- // not identity: truncating it costs a merge, and canMergeWith compares in full.+ // ~0.004 around z=10) and leaves material 5; opaque keeps depth at 14 and material+ // 11. One trade twice: depth is what the eye sees, material only what batches well.if (blended) {- return layerKey | stageKey- | (static_cast<u64>(orderedDepth >> 12) << 24)- | (static_cast<u64>(shaderId & 0xFF) << 16)- | (static_cast<u64>(blend) << 13)- | (static_cast<u64>(stateFlags & 0x03) << 11)- | (static_cast<u64>(materialId) & 0x7FF);+ return layerKey | orderBits(order) | stageKey+ | (static_cast<u64>(orderedDepth >> 12) << 18)+ | (static_cast<u64>(shaderId & 0xFF) << 10)+ | (blendBits(blend) << 7)+ | (static_cast<u64>(stateFlags & 0x03) << 5)+ | (static_cast<u64>(materialId) & 0x1F);}- return layerKey | stageKey- | (static_cast<u64>(shaderId & 0xFF) << 36)- | (static_cast<u64>(blend) << 33)- | (static_cast<u64>(stateFlags & 0x03) << 31)- | ((static_cast<u64>(materialId) & 0x1FFFF) << 14)+ return layerKey | orderBits(order) | stageKey+ | (static_cast<u64>(shaderId & 0xFF) << 30)+ | (blendBits(blend) << 27)+ | (static_cast<u64>(stateFlags & 0x03) << 25)+ | ((static_cast<u64>(materialId) & 0x7FF) << 14)| static_cast<u64>(orderedDepth >> 18);}+ /** @brief The blend field, 3 bits wide wherever it appears.+ * @details Masked, because the enum outgrew the field: BlendMode::None is 9, and+ * unmasked it set a bit in the SHADER field above it. Aliasing None onto+ * Additive costs a merge; the spill cost a wrong order. */+ static u64 blendBits(BlendMode blend) {+ return static_cast<u64>(blend) & 0x7;+ }++ /** @brief The order field at [47:40], biased so a negative order sorts below zero.+ * @details CLAMPED, not wrapped: an order past the range pins to the extreme it ran+ * past, where a wrap would land it on the far side — "very much on top"+ * turning into "behind everything" is the one failure a clamp cannot make. */+ static u64 orderBits(i32 order) {+ return static_cast<u64>(std::clamp(order + 128, 0, 255)) << 40;+ }+// Order-preserving float → u32: flip the sign bit for positives, all bits for// negatives, so unsigned compare matches float compare (finite values).static u32 orderedFloatBits(f32 v) {@@ -189,31 +212,35 @@ struct DrawCommand {return (bits & 0x80000000u) ? ~bits : (bits | 0x80000000u);}- // Y-sorted variant (top-down occlusion): within a layer the painter's order by- // world Y dominates everything — higher Y (further "back" under Y-up) draws- // first, so lower-on-screen entities land on top. Material/depth leave the key- // (Y-order beats batching by design; adjacent same-state runs still merge in- // finalize), shader/blend/flags remain as tie-breaks so equal-Y draws group.- // Same top two fields as buildSortKey, so a y-sorted layer and a plain one order+ // Y-sorted variant (top-down occlusion): higher Y (further "back" under Y-up) draws+ // first, so lower-on-screen entities land on top. Material and depth leave the key;+ // shader/blend/flags stay as tie-breaks so equal-Y draws group for the merge.++ // Same top three fields as buildSortKey, so a y-sorted layer and a plain one order// correctly against each other; below them this spends its bits on worldY instead.- //- // [63:48] layer | [47:44] stage | [43:20] worldY | [19:12] shader- // [11:9] blend | [8:7] flags++ // Order outranks worldY because y-sort INFERS an order from position and an author+ // stating one is overriding that inference. Without it a y-sorted layer has no+ // override at all: z never reaches this key, so a shadow cannot be pinned under its owner.++ // [63:48] layer | [47:40] order | [39:38] stage | [37:14] worldY+ // [13:6] shader | [5:3] blend | [2:1] flagsstatic u64 buildSortKeyYSorted(RenderStage stage, i32 layer, f32 worldY,- u32 shaderId, BlendMode blend, u16 stateFlags) {+ u32 shaderId, BlendMode blend, u16 stateFlags,+ i32 order = 0) {i32 normalizedLayer = std::clamp(layer + 32768, 0, 65535);u64 layerKey = static_cast<u64>(normalizedLayer & 0xFFFF) << 48;- u64 stageKey = static_cast<u64>(stage) << 44;+ u64 stageKey = static_cast<u64>(stage) << 38;u32 yDescending = (~orderedFloatBits(worldY)) >> 8; // 24 bits, larger Y → smaller key- u64 yKey = static_cast<u64>(yDescending & 0xFFFFFF) << 20;+ u64 yKey = static_cast<u64>(yDescending & 0xFFFFFF) << 14;- u64 shaderKey = static_cast<u64>(shaderId & 0xFF) << 12;- u64 blendKey = static_cast<u64>(blend) << 9;- u64 flagsKey = static_cast<u64>(stateFlags & 0x03) << 7;+ u64 shaderKey = static_cast<u64>(shaderId & 0xFF) << 6;+ u64 blendKey = blendBits(blend) << 3;+ u64 flagsKey = static_cast<u64>(stateFlags & 0x03) << 1;- return stageKey | layerKey | yKey | shaderKey | blendKey | flagsKey;+ return stageKey | layerKey | orderBits(order) | yKey | shaderKey | blendKey | flagsKey;}/** @brief Finds @p texId in this command's texture set, adds it (returns its slot), ordiff --git a/src/esengine/renderer/plugins/SpritePlugin.cpp b/src/esengine/renderer/plugins/SpritePlugin.cppindex 816490d39..c47b61748 100644--- a/src/esengine/renderer/plugins/SpritePlugin.cpp+++ b/src/esengine/renderer/plugins/SpritePlugin.cpp@@ -90,6 +90,7 @@ void SpritePlugin::collect(RenderCollectContext& collect_ctx) {BatchDrawKey key{.stage = ctx.current_stage,.layer = sprite.layer,+ .order = sprite.order,.shaderId = batch_shader_id_,.blend = BlendMode::Normal,.textureId = textureId,diff --git a/tests/aot/generated/conformance/handshake.h b/tests/aot/generated/conformance/handshake.hindex 3290a4086..3cea771a4 100644--- a/tests/aot/generated/conformance/handshake.h+++ b/tests/aot/generated/conformance/handshake.h@@ -1,5 +1,5 @@/* GENERATED by sdk/tests/aot-conformance.test.ts — do not edit. *//* The contract half of the handshake. The width half is the harness. */-#define ES_CONF_EXPECTED_CONTRACT_HASH 0x8b1250b915a86114ULL+#define ES_CONF_EXPECTED_CONTRACT_HASH 0x681b5793a937f90bULL/* And which BUILD the artifact beside this one is. */#define ES_CONF_EXPECTED_MODULE_CONTRACT 0xc3d0e057d5701a2eULLdiff --git a/tests/aot/generated/conformance/systems_decl.c b/tests/aot/generated/conformance/systems_decl.cindex 5e52c3589..92e67c694 100644--- a/tests/aot/generated/conformance/systems_decl.c+++ b/tests/aot/generated/conformance/systems_decl.c@@ -10,7 +10,7 @@answer, it is a read of a different field. The address width belongsto the MACHINE, so it mixes in here rather than in the compiler and a32-bit artifact cannot load into a 64-bit host. */-#define ES_ABI_ENGINE_DIGEST 0x8b1250b915a86114ULL+#define ES_ABI_ENGINE_DIGEST 0x681b5793a937f90bULLES_EXPORT const uint64_t es_abi_hash =ES_ABI_ENGINE_DIGEST ^ (0x9e3779b97f4a7c15ULL * (uint64_t)sizeof(es_addr_t));diff --git a/tests/renderer/test_batch_builder.cpp b/tests/renderer/test_batch_builder.cppindex 178f92151..9c6ee7d9c 100644--- a/tests/renderer/test_batch_builder.cpp+++ b/tests/renderer/test_batch_builder.cpp@@ -630,6 +630,185 @@ TEST_CASE("depth layer: y-sort wins when a layer declares both") {CHECK(h.list.layerOrder(5) == DrawList::LayerOrder::Painter);}+// ─── Order within a layer ────────────────────────────────────────────────────+// The author's explicit answer to "what is on top of what", inside one layer. Each case+// below is one the layer's own ordering gets wrong on purpose, so it measures an override.++// Each pair gets two shaders, which keeps them from coalescing into one multi-texture+// draw and leaves their order observable. Shader ranks below every field under test.++TEST_CASE("order: a higher order draws on top of a nearer sprite") {+ Harness h;+ BatchVertex quad[4] = {};++ BatchDrawKey near = quadKey(1, /*layer=*/3);+ near.depth = 50.0f; // nearest — depth alone would put it last+ BatchDrawKey far = quadKey(2, /*layer=*/3);+ far.depth = -50.0f;+ far.order = 1;+ far.shaderId = 8;++ appendQuad(h.pool, h.list, h.clips, quad, near);+ appendQuad(h.pool, h.list, h.clips, quad, far);+ h.list.finalize(h.pool);++ REQUIRE(h.list.mergedDrawCallCount() == 2);+ CHECK(h.list.command(0).texture_ids[0] == 1);+ CHECK(h.list.command(1).texture_ids[0] == 2);+}++// The gap this field was added for. A y-sorted layer drops z from the key entirely, so+// before this there was NO way to pin a draw inside one — a shadow that must stay under+// its owner had only the owner's own Y to argue with.+TEST_CASE("order: inside a y-sorted layer, a stated order beats world Y") {+ Harness h;+ h.list.setYSortMask(1u << 4);+ BatchVertex quad[4] = {};++ // Lower Y draws last under y-sort, so this one would land on top unaided.+ BatchDrawKey low = quadKey(1, /*layer=*/4);+ low.y = -100.0f;+ BatchDrawKey high = quadKey(2, /*layer=*/4);+ high.y = 100.0f;+ high.order = 1;+ high.shaderId = 8;++ appendQuad(h.pool, h.list, h.clips, quad, low);+ appendQuad(h.pool, h.list, h.clips, quad, high);+ h.list.finalize(h.pool);++ REQUIRE(h.list.mergedDrawCallCount() == 2);+ CHECK(h.list.command(0).texture_ids[0] == 1);+ CHECK(h.list.command(1).texture_ids[0] == 2);+}++// Y-sort still orders everything the author did not speak for. Without this, a field+// that simply disabled y-sort would pass every other case here.+TEST_CASE("order: equal orders leave y-sort to decide") {+ Harness h;+ h.list.setYSortMask(1u << 4);+ BatchVertex quad[4] = {};++ BatchDrawKey low = quadKey(1, /*layer=*/4); low.y = -100.0f;+ BatchDrawKey high = quadKey(2, /*layer=*/4); high.y = 100.0f; high.shaderId = 8;+ low.order = high.order = 5; // stated, and stated the same++ appendQuad(h.pool, h.list, h.clips, quad, low);+ appendQuad(h.pool, h.list, h.clips, quad, high);+ h.list.finalize(h.pool);++ REQUIRE(h.list.mergedDrawCallCount() == 2);+ CHECK(h.list.command(0).texture_ids[0] == 2); // higher Y is further back+ CHECK(h.list.command(1).texture_ids[0] == 1);+}++// An order is a promise about one layer's contents, never about the layer itself.+TEST_CASE("order: the largest order never escapes its own layer") {+ Harness h;+ BatchVertex quad[4] = {};++ BatchDrawKey shouted = quadKey(1, /*layer=*/3);+ shouted.order = 127;+ BatchDrawKey above = quadKey(2, /*layer=*/4);+ above.order = -128;+ above.shaderId = 8;++ appendQuad(h.pool, h.list, h.clips, quad, shouted);+ appendQuad(h.pool, h.list, h.clips, quad, above);+ h.list.finalize(h.pool);++ REQUIRE(h.list.mergedDrawCallCount() == 2);+ CHECK(h.list.command(0).layer == 3);+ CHECK(h.list.command(1).layer == 4);+}++// Biased, not masked: -1 has to land below 0 rather than wrapping to the top of the+// field, which is what a two's-complement cast into the key would have done.+TEST_CASE("order: a negative order sinks below an unstated one") {+ Harness h;+ BatchVertex quad[4] = {};++ BatchDrawKey plain = quadKey(1, /*layer=*/3);+ BatchDrawKey behind = quadKey(2, /*layer=*/3);+ behind.order = -1;+ behind.shaderId = 8;++ appendQuad(h.pool, h.list, h.clips, quad, plain);+ appendQuad(h.pool, h.list, h.clips, quad, behind);+ h.list.finalize(h.pool);++ REQUIRE(h.list.mergedDrawCallCount() == 2);+ CHECK(h.list.command(0).texture_ids[0] == 2);+ CHECK(h.list.command(1).texture_ids[0] == 1);+}++// Clamped, not wrapped. A project ported from an engine with a wider range keeps the+// SIGN of what it asked for: "far on top" degrades to "on top", never to "behind".+TEST_CASE("order: an order past the range pins to the end it ran past") {+ Harness h;+ BatchVertex quad[4] = {};++ BatchDrawKey huge = quadKey(1, /*layer=*/3);+ huge.order = 32000;+ BatchDrawKey tiny = quadKey(2, /*layer=*/3);+ tiny.order = -32000;+ tiny.shaderId = 8;++ appendQuad(h.pool, h.list, h.clips, quad, huge);+ appendQuad(h.pool, h.list, h.clips, quad, tiny);+ h.list.finalize(h.pool);++ REQUIRE(h.list.mergedDrawCallCount() == 2);+ CHECK(h.list.command(0).texture_ids[0] == 2);+ CHECK(h.list.command(1).texture_ids[0] == 1);+}++// Order outranks stage for the same reason layer does: it is a promise the author made,+// and a stage is only how a layer groups what it holds. An opaque draw the author put+// underneath must stay underneath, early-z or not.+TEST_CASE("order: a blended draw ordered below an opaque one still draws first") {+ Harness h;+ BatchVertex quad[4] = {};++ BatchDrawKey blended = quadKey(1, /*layer=*/3);+ blended.order = -1;+ BatchDrawKey opaque = quadKey(2, /*layer=*/3);+ opaque.stage = RenderStage::Opaque;+ opaque.shaderId = 8;++ appendQuad(h.pool, h.list, h.clips, quad, opaque);+ appendQuad(h.pool, h.list, h.clips, quad, blended);+ h.list.finalize(h.pool);++ REQUIRE(h.list.mergedDrawCallCount() == 2);+ CHECK(h.list.command(0).texture_ids[0] == 1);+ CHECK(h.list.command(1).texture_ids[0] == 2);+}++// BlendMode::None is 9 and the key's blend field is 3 bits, so unmasked it set a bit in+// the SHADER field above it. Painter-ordered on purpose: a depth layer routes a None+// blend to the Opaque stage, never reaching the blended packing where the spill showed.+TEST_CASE("sort key: an opaque blend mode cannot reach the shader field") {+ Harness h;+ BatchVertex quad[4] = {};++ BatchDrawKey none = quadKey(1, /*layer=*/3);+ none.blend = BlendMode::None;+ BatchDrawKey normal = quadKey(2, /*layer=*/3);++ // Same shader, same depth, same everything the key ranks above blend: whatever+ // separates them is the blend field, and it may not reach past its own 3 bits.+ CHECK((DrawCommand::buildSortKey(RenderStage::Transparent, 3, none.shaderId,+ BlendMode::None, 0, 0.0f) >> 10)+ == (DrawCommand::buildSortKey(RenderStage::Transparent, 3, normal.shaderId,+ BlendMode::Normal, 0, 0.0f) >> 10));++ appendQuad(h.pool, h.list, h.clips, quad, none);+ appendQuad(h.pool, h.list, h.clips, quad, normal);+ h.list.finalize(h.pool);+ REQUIRE(h.list.mergedDrawCallCount() == 2);+}+// ─── Stencil mask ordering ───────────────────────────────────────────────────// A stencil write must precede the draws that test it, and the sort key holds no// clip state. The layer does it: UI pre-order puts a parent below its descendants.diff --git a/tools/eht/generators/metadata.py b/tools/eht/generators/metadata.pyindex f008cebd4..35d906577 100644--- a/tools/eht/generators/metadata.py+++ b/tools/eht/generators/metadata.py@@ -324,7 +324,10 @@ class MetadataGenerator:used_base.add(base)elif base in self.types.CUSTOM_STRUCTS or base in self._enum_ts_names():used_struct.add(base)- field_lines.append(f' {prop.name}: {ts};')+ # `optional` relaxes the WRITE side only: the struct always has the+ # field, and a reader gets the default. See parser.FLAG_ANNOTATIONS.+ mark = '?' if 'optional' in prop.annotations else ''+ field_lines.append(f' {prop.name}{mark}: {ts};')# The SDK's tier, from ES_COMPONENT(stability=). It has to sit on the# declaration: a release tag in this file's header would not survive# the declaration bundle a project compiles against.diff --git a/tools/eht/parser.py b/tools/eht/parser.pyindex e61196d41..2a25e5dd0 100644--- a/tools/eht/parser.py+++ b/tools/eht/parser.py@@ -48,6 +48,11 @@ class CppParser:FLAG_ANNOTATIONS = frozenset({'animatable', 'anim_override', 'entity_ref', 'readonly','slider', 'advanced', 'skip_serialize', 'replicated',+ # Marks the field OPTIONAL in the generated `<Name>Data` interface. What a+ # field added to a component already frozen `stability=public` needs: the+ # struct always carries it, but `world.set` takes the whole interface, so a+ # required member would stop code written before the field from compiling.+ 'optional',# An enum-typed field renders as a multi-select bitmask instead of a single-# choice dropdown; suppresses the auto-generated `enum` options (the bit list# is curated in TS — combined values like ColorAndDepth aren't single bits).