Skip to content

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.

refactor(editor): a field says which states of its component it belongs to

yhhf37b9ca99834
diff --git a/CHANGELOG.md b/CHANGELOG.md
index fab6c776e..37f5aff2d 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -140,6 +140,33 @@ published separately; it ships inside the editor.
### Changed
+- **A field says which states of its component it belongs to, where the field is.** The
+ inspector hid the fields that are inert in a component's current state — a Spot's cone
+ angles on a Point light, a trail's tuning with the trail off — from a switch in the
+ editor's TypeScript: four components, seventeen rules, each written as a bare enum
+ number (`type !== 3`, `shape === 0 || shape === 2`) in a language that cannot see the
+ C++ enum those numbers come from. Two places knowing one thing, and the second one
+ knowing it by ordinal.
+
+ `shown_when=<field>:<State>|<State>` is authored at the C++ ES_PROPERTY site now,
+ beside the range and the tooltip that already live there, and it names STATES:
+ `shown_when=type:Point|Spot`, `shown_when=trailEnabled:true`. The generator resolves
+ the names against that discriminator's own enum and ships the numbers the data stores,
+ so reordering an enum moves every rule with it, and a state that enum has no member of
+ is a build failure rather than a 0. The editor's switch is gone: what is left reads the
+ rule off the field and knows no component's name.
+
+ Twenty rules now, where there were seventeen. Light2D gained the three the switch never
+ had — `sourceAngle`, `shadowExtent` and `meshShadows` are a sun's, an environment is an
+ Ambient light's — which is what makes the component read as one kind of light at a time
+ rather than the union of all four.
+
+ Verified in both directions on the existing behavioural suite (`inspector-conditional-
+ fields`, 14 tests that pass unchanged against the derived implementation, and 5 new
+ ones): a rule aimed one state off turns three of them red, a state the enum does not
+ have stops the generator with the enum named, and a discriminator that is not a field
+ stops it before codegen.
+
- **A shadow's depth bias is derived where it is used, out of what the map covers
there.** It was computed per tile on the CPU — a constant, times the tile's coverage,
over its side, times its coverage again, times how much depth a world unit is worth at
diff --git a/desktop/src/engine/schema.ts b/desktop/src/engine/schema.ts
index edbed8318..e0052ac54 100644
--- a/desktop/src/engine/schema.ts
+++ b/desktop/src/engine/schema.ts
@@ -1,6 +1,6 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
-import { getComponentRegistry, getUserComponents, getComponent, getComponentAssetFieldDescriptors, getComponentSkeletalFieldDescriptor, getComponentFieldMeta, Light2DType, usesStagger, isHexOrientation, q } from 'esengine';
+import { getComponentRegistry, getUserComponents, getComponent, getComponentAssetFieldDescriptors, getComponentSkeletalFieldDescriptor, getComponentFieldMeta, Light2DType, q } from 'esengine';
import type { App, SceneData } from 'esengine';
import type { NodeKind, EntityId, InspectorField, InspectorFieldValue, EnumOption, GradientValue, CurveValue } from '@/types';
import { t } from '@/i18n';
@@ -753,57 +753,17 @@ function fieldFor(
* registered default. The caller diffs `value` vs `defaultValue` to mark
* overrides; an entity with no prefab base just compares against the default.
*/
-// Fields that only apply to some states of the SAME component — hidden from the
-// inspector when inert so the panel shows just the controls that matter, gated on a
-// sibling discriminator field's live value. Each rule hides ONLY a field that is
-// definitively meaningless in the current state (never one that merely defaults),
-// so switching the discriminator back brings the field (and its stored value) right
-// back. `data` here is the effective view (stored values over registered defaults),
-// so a discriminator omitted from the stored data still resolves.
+// A field inert in the component's current state is hidden, and which states it
+// belongs to is declared beside it at the C++ ES_PROPERTY site — so this knows the
+// rule without knowing one component. Hiding never touches the stored value.
function isConditionallyHidden(compType: string, key: string, data: Record<string, unknown>): boolean {
- switch (compType) {
- case 'TilemapLayer': {
- const orientation = Number(data.orientation) || 0;
- if (key === 'hexSideLength') return !isHexOrientation(orientation);
- if (key === 'staggerAxis' || key === 'staggerIndex') return !usesStagger(orientation);
- return false;
- }
- case 'Camera': {
- // projectionType: Perspective = 0, Orthographic = 1.
- const ortho = Number(data.projectionType) === 1;
- if (key === 'fov') return ortho; // an ortho projection has no field of view
- if (key === 'orthoSize') return !ortho; // ortho-only half-height
- if (key === 'pixelPerfect') return !ortho; // pixel snap is an ortho pixel-art concern
- return false;
- }
- case 'Light2D': {
- // type: Point = 0, Directional = 1, Ambient = 2, Spot = 3.
- const type = Number(data.type) || 0;
- if (key === 'radius') return type === 1 || type === 2; // Point / Spot reach only
- if (key === 'innerAngle' || key === 'outerAngle') return type !== 3; // Spot cone only
- if (key === 'shadowDistance') return type !== 1; // Directional shadow only
- if (key === 'shadowSoftness') return type === 2; // Ambient casts no shadow
- return false;
- }
- case 'ParticleEmitter': {
- // shape: Point = 0, Circle = 1, Rectangle = 2, Cone = 3 (Circle & Cone use the
- // radius; Rectangle the size; Cone the angle — see the emitter shape gizmo).
- const shape = Number(data.shape) || 0;
- if (key === 'shapeRadius') return shape === 0 || shape === 2;
- if (key === 'shapeSize') return shape !== 2;
- if (key === 'shapeAngle') return shape !== 3;
- // A disabled trail / floor collision hides its whole tuning block.
- if (key === 'trailWidth' || key === 'trailPoints' || key === 'trailMinDistance') {
- return data.trailEnabled === false;
- }
- if (key === 'collisionFloor' || key === 'collisionBounce' || key === 'collisionFriction' || key === 'collisionLifetimeLoss') {
- return data.collisionEnabled === false;
- }
- return false;
- }
- default:
- return false;
- }
+ const shownWhen = getComponentFieldMeta(compType)[key]?.shownWhen;
+ if (!shownWhen) return false;
+ const state = data[shownWhen.field];
+ // Nothing to judge it by — `data` is the effective view, so this is a component
+ // whose discriminator is not a field at all. Show the control rather than hide it.
+ if (state === undefined || state === null) return false;
+ return !shownWhen.values.includes(typeof state === 'boolean' ? Number(state) : Number(state));
}
export function inspectorFields(
diff --git a/desktop/tests/inspector-conditional-fields.test.ts b/desktop/tests/inspector-conditional-fields.test.ts
index dc09c2c3a..ada503e77 100644
--- a/desktop/tests/inspector-conditional-fields.test.ts
+++ b/desktop/tests/inspector-conditional-fields.test.ts
@@ -3,11 +3,13 @@
/**
* @file Conditional field visibility — the Details panel hides fields that are
* inert in a component's current state (Camera projection, Light2D type,
- * ParticleEmitter shape/trail/collision), gated on a sibling discriminator.
- * Exercised through the builtin registry (no WASM). A rule must hide a field
- * ONLY when it is meaningless, and bring it back when the discriminator flips.
+ * ParticleEmitter shape/trail/collision), gated on a sibling discriminator
+ * each field names for itself at its C++ ES_PROPERTY site. Exercised through
+ * the builtin registry (no WASM). A rule must hide a field ONLY when it is
+ * meaningless, and bring it back when the discriminator flips.
*/
import { describe, it, expect } from 'vitest';
+import { getComponentFieldMeta } from 'esengine';
import { inspectorFields } from '@/engine/schema';
/** The visible field keys the inspector would render for `data`. */
@@ -65,6 +67,47 @@ describe('conditional inspector fields', () => {
});
});
+ describe('Light2D type — what belongs to each kind of light', () => {
+ it('Directional: the sun\'s own coverage and angular size, and no environment', () => {
+ const k = keys('Light2D', { type: 1 });
+ expect(k.has('sourceAngle')).toBe(true);
+ expect(k.has('shadowExtent')).toBe(true);
+ expect(k.has('meshShadows')).toBe(true);
+ expect(k.has('environment')).toBe(false);
+ expect(k.has('drawEnvironment')).toBe(false);
+ });
+ it('Ambient: the environment it casts, and nothing about casting shadows', () => {
+ const k = keys('Light2D', { type: 2 });
+ expect(k.has('environment')).toBe(true);
+ expect(k.has('drawEnvironment')).toBe(true);
+ expect(k.has('meshShadows')).toBe(false);
+ expect(k.has('shadowExtent')).toBe(false);
+ expect(k.has('sourceAngle')).toBe(false);
+ });
+ it('Spot: a map it can cast, but not a sun\'s coverage or angle', () => {
+ const k = keys('Light2D', { type: 3 });
+ expect(k.has('meshShadows')).toBe(true);
+ expect(k.has('shadowSoftness')).toBe(true);
+ expect(k.has('sourceAngle')).toBe(false);
+ expect(k.has('shadowExtent')).toBe(false);
+ });
+ });
+
+ describe('the rule travels with the field, not with the panel', () => {
+ it('a field carries the states it belongs to, by the number the data stores', () => {
+ expect(getComponentFieldMeta('Light2D').innerAngle?.shownWhen)
+ .toEqual({ field: 'type', values: [3] });
+ expect(getComponentFieldMeta('ParticleEmitter').trailWidth?.shownWhen)
+ .toEqual({ field: 'trailEnabled', values: [1] });
+ });
+ it('a field that names no state is shown whatever the discriminator says', () => {
+ expect(getComponentFieldMeta('Light2D').intensity?.shownWhen).toBeUndefined();
+ for (const type of [0, 1, 2, 3]) {
+ expect(keys('Light2D', { type }).has('intensity')).toBe(true);
+ }
+ });
+ });
+
describe('ParticleEmitter shape', () => {
it('Point: no shape geometry fields', () => {
const k = keys('ParticleEmitter', { shape: 0 });
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index 2e55b6b5f..12e895078 100644
--- a/sdk/etc/index.api.md
+++ b/sdk/etc/index.api.md
@@ -3082,6 +3082,7 @@ map: boolean | undefined
max: number | undefined
min: number | undefined
normalizedOf: string | undefined
+shownWhen: { field: string; values: ReadonlyArray<number>; } | undefined
slider: boolean | undefined
step: number | undefined
tooltip: string | undefined
diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.md
index 688f0ce50..3d3f9aa85 100644
--- a/sdk/etc/index.native.api.md
+++ b/sdk/etc/index.native.api.md
@@ -3090,6 +3090,7 @@ map: boolean | undefined
max: number | undefined
min: number | undefined
normalizedOf: string | undefined
+shownWhen: { field: string; values: ReadonlyArray<number>; } | undefined
slider: boolean | undefined
step: number | undefined
tooltip: string | undefined
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index eba1dfdad..b308b26c2 100644
--- a/sdk/etc/index.node.api.md
+++ b/sdk/etc/index.node.api.md
@@ -3077,6 +3077,7 @@ map: boolean | undefined
max: number | undefined
min: number | undefined
normalizedOf: string | undefined
+shownWhen: { field: string; values: ReadonlyArray<number>; } | undefined
slider: boolean | undefined
step: number | undefined
tooltip: string | undefined
diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.md
index 507d308ae..846565930 100644
--- a/sdk/etc/minigame.api.md
+++ b/sdk/etc/minigame.api.md
@@ -3077,6 +3077,7 @@ map: boolean | undefined
max: number | undefined
min: number | undefined
normalizedOf: string | undefined
+shownWhen: { field: string; values: ReadonlyArray<number>; } | undefined
slider: boolean | undefined
step: number | undefined
tooltip: string | undefined
diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.md
index 74d536477..85a6b4c8b 100644
--- a/sdk/etc/wechat.api.md
+++ b/sdk/etc/wechat.api.md
@@ -3077,6 +3077,7 @@ map: boolean | undefined
max: number | undefined
min: number | undefined
normalizedOf: string | undefined
+shownWhen: { field: string; values: ReadonlyArray<number>; } | undefined
slider: boolean | undefined
step: number | undefined
tooltip: string | undefined
diff --git a/sdk/src/ecs/component.generated.ts b/sdk/src/ecs/component.generated.ts
index 9389de579..a8047c9c1 100644
--- a/sdk/src/ecs/component.generated.ts
+++ b/sdk/src/ecs/component.generated.ts
@@ -173,14 +173,14 @@ export const COMPONENT_META: Record<string, ComponentMetaEntry> = {
animatableFields: ['orthoSize'],
fields: {
projectionType: { enum: [{ label: 'Perspective', value: 0 }, { label: 'Orthographic', value: 1 }], tooltip: "Orthographic (2D) or Perspective projection." },
- fov: { min: 1, max: 179, unit: "°" },
- orthoSize: { min: 0, tooltip: "Half the visible height in world units (Orthographic)." },
+ fov: { min: 1, max: 179, unit: "°", shownWhen: { field: "projectionType", values: [0] } },
+ orthoSize: { min: 0, tooltip: "Half the visible height in world units (Orthographic).", shownWhen: { field: "projectionType", values: [1] } },
nearPlane: { min: 0, advanced: true },
farPlane: { min: 0, advanced: true },
aspectRatio: { advanced: true },
priority: { step: 1, advanced: true },
clearFlags: { tooltip: "Which buffers to clear before rendering this camera." },
- pixelPerfect: { tooltip: "Snap the camera to the pixel grid for crisp pixel-art (Orthographic).", advanced: true },
+ pixelPerfect: { tooltip: "Snap the camera to the pixel grid for crisp pixel-art (Orthographic).", advanced: true, shownWhen: { field: "projectionType", values: [1] } },
cullingMask: { tooltip: "Which sorting layers this camera renders.", bitmask: { source: "sortingLayers" } },
},
},
@@ -411,16 +411,16 @@ export const COMPONENT_META: Record<string, ComponentMetaEntry> = {
fields: {
type: { enum: [{ label: 'Point', value: 0 }, { label: 'Directional', value: 1 }, { label: 'Ambient', value: 2 }, { label: 'Spot', value: 3 }], tooltip: "Point, Directional, Ambient, or Spot." },
intensity: { min: 0, tooltip: "Brightness multiplier of the light." },
- radius: { min: 0, tooltip: "Falloff reach in world units (Point / Spot)." },
- innerAngle: { min: 0, max: 180, unit: "°", advanced: true },
- outerAngle: { min: 0, max: 180, unit: "°", advanced: true },
- shadowSoftness: { min: 0, tooltip: "Shadow softness (light-source size); 0 = hard edge." },
- sourceAngle: { min: 0, max: 90, unit: "°", tooltip: "Angular size of a Directional light's source; 0 = hard edge (sun ~0.53).", advanced: true },
- shadowDistance: { min: 0, tooltip: "Directional shadow distance; 0 = no directional shadow.", advanced: true },
- meshShadows: { tooltip: "Cast a shadow map over 3D meshes (Directional, Spot, Point)." },
- shadowExtent: { min: 0, tooltip: "Shadow map coverage radius; 0 = fit the view.", advanced: true },
- environment: { tooltip: "Baked environment (.esenv) this Ambient light casts." },
- drawEnvironment: { tooltip: "Draw this environment as the sky behind the scene." },
+ radius: { min: 0, tooltip: "Falloff reach in world units (Point / Spot).", shownWhen: { field: "type", values: [0, 3] } },
+ innerAngle: { min: 0, max: 180, unit: "°", advanced: true, shownWhen: { field: "type", values: [3] } },
+ outerAngle: { min: 0, max: 180, unit: "°", advanced: true, shownWhen: { field: "type", values: [3] } },
+ shadowSoftness: { min: 0, tooltip: "Shadow softness (light-source size); 0 = hard edge.", shownWhen: { field: "type", values: [0, 1, 3] } },
+ sourceAngle: { min: 0, max: 90, unit: "°", tooltip: "Angular size of a Directional light's source; 0 = hard edge (sun ~0.53).", advanced: true, shownWhen: { field: "type", values: [1] } },
+ shadowDistance: { min: 0, tooltip: "Directional shadow distance; 0 = no directional shadow.", advanced: true, shownWhen: { field: "type", values: [1] } },
+ meshShadows: { tooltip: "Cast a shadow map over 3D meshes (Directional, Spot, Point).", shownWhen: { field: "type", values: [0, 1, 3] } },
+ shadowExtent: { min: 0, tooltip: "Shadow map coverage radius; 0 = fit the view.", advanced: true, shownWhen: { field: "type", values: [1] } },
+ environment: { tooltip: "Baked environment (.esenv) this Ambient light casts.", shownWhen: { field: "type", values: [2] } },
+ drawEnvironment: { tooltip: "Draw this environment as the sky behind the scene.", shownWhen: { field: "type", values: [2] } },
},
},
Mesh2D: {
@@ -570,9 +570,9 @@ export const COMPONENT_META: Record<string, ComponentMetaEntry> = {
lifetimeMin: { min: 0, category: "Lifetime" },
lifetimeMax: { min: 0, category: "Lifetime" },
shape: { enum: [{ label: 'Point', value: 0 }, { label: 'Circle', value: 1 }, { label: 'Rectangle', value: 2 }, { label: 'Cone', value: 3 }], category: "Shape" },
- shapeRadius: { min: 0, category: "Shape" },
- shapeSize: { category: "Shape" },
- shapeAngle: { unit: "°", category: "Shape" },
+ shapeRadius: { min: 0, category: "Shape", shownWhen: { field: "shape", values: [1, 3] } },
+ shapeSize: { category: "Shape", shownWhen: { field: "shape", values: [2] } },
+ shapeAngle: { unit: "°", category: "Shape", shownWhen: { field: "shape", values: [3] } },
speedMin: { category: "Velocity" },
speedMax: { category: "Velocity" },
angleSpreadMin: { unit: "°", category: "Velocity" },
@@ -609,14 +609,14 @@ export const COMPONENT_META: Record<string, ComponentMetaEntry> = {
subEmitterInheritVelocity: { min: 0, max: 1, category: "SubEmitter" },
subEmitter: { category: "SubEmitter" },
trailEnabled: { category: "Trail" },
- trailWidth: { min: 0, category: "Trail" },
- trailPoints: { min: 2, max: 12, step: 1, category: "Trail" },
- trailMinDistance: { min: 0, category: "Trail" },
+ trailWidth: { min: 0, category: "Trail", shownWhen: { field: "trailEnabled", values: [1] } },
+ trailPoints: { min: 2, max: 12, step: 1, category: "Trail", shownWhen: { field: "trailEnabled", values: [1] } },
+ trailMinDistance: { min: 0, category: "Trail", shownWhen: { field: "trailEnabled", values: [1] } },
collisionEnabled: { category: "Collision" },
- collisionFloor: { category: "Collision" },
- collisionBounce: { min: 0, max: 1, category: "Collision" },
- collisionFriction: { min: 0, max: 1, category: "Collision" },
- collisionLifetimeLoss: { min: 0, max: 1, category: "Collision" },
+ collisionFloor: { category: "Collision", shownWhen: { field: "collisionEnabled", values: [1] } },
+ collisionBounce: { min: 0, max: 1, category: "Collision", shownWhen: { field: "collisionEnabled", values: [1] } },
+ collisionFriction: { min: 0, max: 1, category: "Collision", shownWhen: { field: "collisionEnabled", values: [1] } },
+ collisionLifetimeLoss: { min: 0, max: 1, category: "Collision", shownWhen: { field: "collisionEnabled", values: [1] } },
},
},
ParticleForceField: {
@@ -846,9 +846,9 @@ export const COMPONENT_META: Record<string, ComponentMetaEntry> = {
animatableFields: ['tintColor.r', 'tintColor.g', 'tintColor.b', 'tintColor.a', 'opacity'],
fields: {
orientation: { enum: [{ label: 'Orthogonal', value: 0 }, { label: 'Isometric', value: 1 }, { label: 'Staggered', value: 2 }, { label: 'Hexagonal', value: 3 }], tooltip: "Grid layout: orthogonal, isometric, staggered, or hexagonal." },
- hexSideLength: { min: 0, step: 1, tooltip: "Hexagonal side length in px (0 = a regular pointy hex = tileHeight/2). Ignored unless orientation is Hexagonal." },
- staggerAxis: { enum: [{ label: 'Y', value: 0 }, { label: 'X', value: 1 }], tooltip: "Stagger axis (staggered/hex): Y shifts rows, X shifts columns." },
- staggerIndex: { enum: [{ label: 'Odd', value: 0 }, { label: 'Even', value: 1 }], tooltip: "Which lines carry the half-cell shift (staggered/hex)." },
+ hexSideLength: { min: 0, step: 1, tooltip: "Hexagonal side length in px (0 = a regular pointy hex = tileHeight/2). Ignored unless orientation is Hexagonal.", shownWhen: { field: "orientation", values: [3] } },
+ staggerAxis: { enum: [{ label: 'Y', value: 0 }, { label: 'X', value: 1 }], tooltip: "Stagger axis (staggered/hex): Y shifts rows, X shifts columns.", shownWhen: { field: "orientation", values: [2, 3] } },
+ staggerIndex: { enum: [{ label: 'Odd', value: 0 }, { label: 'Even', value: 1 }], tooltip: "Which lines carry the half-cell shift (staggered/hex).", shownWhen: { field: "orientation", values: [2, 3] } },
tilesetColumns: { min: 1, step: 1 },
renderLayer: { step: 1, enumSource: "sortingLayers" },
opacity: { min: 0, max: 1, slider: true, tooltip: "Layer transparency (0 = invisible, 1 = opaque)." },
diff --git a/sdk/src/ecs/component.ts b/sdk/src/ecs/component.ts
index aeac0d49e..0f5ab8240 100644
--- a/sdk/src/ecs/component.ts
+++ b/sdk/src/ecs/component.ts
@@ -98,6 +98,13 @@ export interface FieldMeta {
* stays the fraction. Authored `normalized_of=` at the C++ ES_PROPERTY site.
*/
normalizedOf?: string;
+ /**
+ * The states of a sibling discriminator this field means anything in — a Spot's
+ * cone angles to `type: Spot`. The inspector hides it elsewhere and leaves the
+ * stored value alone. Authored `shown_when=<field>:<State>` by NAME at the C++
+ * ES_PROPERTY site; the names resolve to stored numbers when this is generated.
+ */
+ shownWhen?: { field: string; values: ReadonlyArray<number> };
/** Human label / tooltip overriding the key-derived ones. */
label?: string;
tooltip?: string;
diff --git a/src/esengine/bindings/EditorAPI.generated.cpp b/src/esengine/bindings/EditorAPI.generated.cpp
index e0236bbd2..488e6cdce 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 03aa2865f562634e
+ * @schema_hash 11f30170ee77e18b
*/
-#define ES_EDITOR_API_SCHEMA_HASH "03aa2865f562634e"
+#define ES_EDITOR_API_SCHEMA_HASH "11f30170ee77e18b"
#include <emscripten/bind.h>
#include <string>
diff --git a/src/esengine/ecs/components/Camera.hpp b/src/esengine/ecs/components/Camera.hpp
index 527251e2d..68561cfbe 100644
--- a/src/esengine/ecs/components/Camera.hpp
+++ b/src/esengine/ecs/components/Camera.hpp
@@ -73,11 +73,12 @@ struct Camera {
ProjectionType projectionType{ProjectionType::Perspective};
/** @brief Field of view in degrees (perspective only) */
- ES_PROPERTY(min=1, max=179, unit="°")
+ ES_PROPERTY(min=1, max=179, unit="°", shown_when=projectionType:Perspective)
f32 fov{60.0f};
/** @brief Orthographic size (half-height in world units) */
- ES_PROPERTY(animatable, min=0, tooltip="Half the visible height in world units (Orthographic).", editor_default=540)
+ ES_PROPERTY(animatable, min=0, shown_when=projectionType:Orthographic,
+ tooltip="Half the visible height in world units (Orthographic).", editor_default=540)
f32 orthoSize{5.0f};
/** @brief Near clipping plane distance */
@@ -111,7 +112,8 @@ struct Camera {
/** @brief Snap the camera to the world-space pixel grid (Orthographic) so static
* pixel art renders crisp, without sub-pixel shimmer when the camera moves. */
- ES_PROPERTY(advanced, tooltip="Snap the camera to the pixel grid for crisp pixel-art (Orthographic).")
+ ES_PROPERTY(advanced, shown_when=projectionType:Orthographic,
+ tooltip="Snap the camera to the pixel grid for crisp pixel-art (Orthographic).")
bool pixelPerfect{false};
/** @brief Sorting layers this camera renders (bit i = layer i). UI belongs to its
diff --git a/src/esengine/ecs/components/Light2D.hpp b/src/esengine/ecs/components/Light2D.hpp
index f184e9ffd..2b71df4b0 100644
--- a/src/esengine/ecs/components/Light2D.hpp
+++ b/src/esengine/ecs/components/Light2D.hpp
@@ -67,36 +67,39 @@ struct Light2D {
f32 intensity{1.0f};
/** @brief Point/Spot falloff radius in world units (ignored by Directional/Ambient). */
- ES_PROPERTY(animatable, min=0, tooltip="Falloff reach in world units (Point / Spot).")
+ ES_PROPERTY(animatable, min=0, shown_when=type:Point|Spot,
+ tooltip="Falloff reach in world units (Point / Spot).")
f32 radius{200.0f};
/** @brief Spot inner cone angle in degrees (full angle; fully lit inside). */
- ES_PROPERTY(animatable, min=0, max=180, unit="°", advanced)
+ ES_PROPERTY(animatable, min=0, max=180, unit="°", advanced, shown_when=type:Spot)
f32 innerAngle{30.0f};
/** @brief Spot outer cone angle in degrees (full angle; fades to dark by here). */
- ES_PROPERTY(animatable, min=0, max=180, unit="°", advanced)
+ ES_PROPERTY(animatable, min=0, max=180, unit="°", advanced, shown_when=type:Spot)
f32 outerAngle{45.0f};
/** @brief Shadow penumbra softness = the light source's half-extent in world units; 0 is a
* hard edge (default). It widens a penumbra the way a bigger source does, and the edge
* sharpens as a caster nears what it falls on. Read by the 2D occluder boxes of every
* type, and by a mesh shadow map only where the light HAS a position (Point/Spot). */
- ES_PROPERTY(animatable, min=0, tooltip="Shadow softness (light-source size); 0 = hard edge.")
+ ES_PROPERTY(animatable, min=0, shown_when=type:Point|Directional|Spot,
+ tooltip="Shadow softness (light-source size); 0 = hard edge.")
f32 shadowSoftness{0.0f};
/** @brief How wide a Directional light's source is, as the angle it subtends — the full
* angular diameter in degrees, 0.53 being the real sun's. A length cannot say it:
* the source is infinitely far away, so only an angle carries a penumbra. 0 is a
* hard edge (default); ignored by the types that have a position and a size. */
- ES_PROPERTY(animatable, min=0, max=90, unit="°", advanced,
+ ES_PROPERTY(animatable, min=0, max=90, unit="°", advanced, shown_when=type:Directional,
tooltip="Angular size of a Directional light's source; 0 = hard edge (sun ~0.53).")
f32 sourceAngle{0.0f};
/** @brief Directional-light shadow reach in world units: how far back toward the light a
* fragment searches for an occluder. 0 = a Directional light casts no shadow (default).
* Ignored by Point/Spot, which shadow along the segment to the light position. */
- ES_PROPERTY(animatable, min=0, advanced, tooltip="Directional shadow distance; 0 = no directional shadow.")
+ ES_PROPERTY(animatable, min=0, advanced, shown_when=type:Directional,
+ tooltip="Directional shadow distance; 0 = no directional shadow.")
f32 shadowDistance{0.0f};
/** @brief Casts a shadow map over 3D meshes. Every type but Ambient can: a
@@ -106,12 +109,14 @@ struct Light2D {
* one light can do both, and a 2.5D scene often wants exactly that. Lights
* that stand somewhere claim their tiles first and one sun takes what is left,
* so a crowded frame costs the sun its farthest cascade rather than a map. */
- ES_PROPERTY(tooltip="Cast a shadow map over 3D meshes (Directional, Spot, Point).")
+ ES_PROPERTY(shown_when=type:Point|Directional|Spot,
+ tooltip="Cast a shadow map over 3D meshes (Directional, Spot, Point).")
bool meshShadows{false};
/** @brief Half-extent of the shadow map's world coverage, centred on the camera.
* 0 = fit what the camera can see. Larger trades sharpness for reach. */
- ES_PROPERTY(min=0, advanced, tooltip="Shadow map coverage radius; 0 = fit the view.")
+ ES_PROPERTY(min=0, advanced, shown_when=type:Directional,
+ tooltip="Shadow map coverage radius; 0 = fit the view.")
f32 shadowExtent{0.0f};
/** @brief What this Ambient light IS, when it is more than one colour: a baked
@@ -119,14 +124,16 @@ struct Light2D {
* flat term it has always been — the same lighting, at order zero.
* @ref color and @ref intensity scale it. Ignored by the other types;
* the first Ambient light that carries one is the frame's environment. */
- ES_PROPERTY(asset = environment, tooltip="Baked environment (.esenv) this Ambient light casts.")
+ ES_PROPERTY(asset = environment, shown_when=type:Ambient,
+ tooltip="Baked environment (.esenv) this Ambient light casts.")
resource::EnvironmentHandle environment;
/** @brief Draw @ref environment as the background as well as reflecting it. Off by
* default, so a scene that adopts an environment for its lighting does not
* also acquire a sky it did not ask for. Ignored without one — and the
* camera still decides whether the background is drawn at all. */
- ES_PROPERTY(tooltip="Draw this environment as the sky behind the scene.")
+ ES_PROPERTY(shown_when=type:Ambient,
+ tooltip="Draw this environment as the sky behind the scene.")
bool drawEnvironment{false};
/** @brief Disabled lights are skipped during collection. */
diff --git a/src/esengine/ecs/components/ParticleEmitter.hpp b/src/esengine/ecs/components/ParticleEmitter.hpp
index d4f67c38b..ad768cf44 100644
--- a/src/esengine/ecs/components/ParticleEmitter.hpp
+++ b/src/esengine/ecs/components/ParticleEmitter.hpp
@@ -78,13 +78,13 @@ struct ParticleEmitter {
ES_PROPERTY(enum=EmitterShape, category=Shape)
i32 shape{static_cast<i32>(EmitterShape::Cone)};
- ES_PROPERTY(min=0, category=Shape)
+ ES_PROPERTY(min=0, category=Shape, shown_when=shape:Circle|Cone)
f32 shapeRadius{100.0f};
- ES_PROPERTY(category=Shape)
+ ES_PROPERTY(category=Shape, shown_when=shape:Rectangle)
glm::vec2 shapeSize{100.0f, 100.0f};
- ES_PROPERTY(unit="°", category=Shape)
+ ES_PROPERTY(unit="°", category=Shape, shown_when=shape:Cone)
f32 shapeAngle{25.0f};
// Velocity
@@ -225,13 +225,13 @@ struct ParticleEmitter {
ES_PROPERTY(category=Trail)
bool trailEnabled{false};
- ES_PROPERTY(min=0, category=Trail)
+ ES_PROPERTY(min=0, category=Trail, shown_when=trailEnabled:true)
f32 trailWidth{8.0f};
- ES_PROPERTY(min=2, max=12, step=1, category=Trail)
+ ES_PROPERTY(min=2, max=12, step=1, category=Trail, shown_when=trailEnabled:true)
i32 trailPoints{6};
- ES_PROPERTY(min=0, category=Trail)
+ ES_PROPERTY(min=0, category=Trail, shown_when=trailEnabled:true)
f32 trailMinDistance{6.0f};
// Collision (Phase 1: a horizontal floor plane) — world-space particles that fall
@@ -241,21 +241,21 @@ struct ParticleEmitter {
ES_PROPERTY(category=Collision)
bool collisionEnabled{false};
- ES_PROPERTY(category=Collision)
+ ES_PROPERTY(category=Collision, shown_when=collisionEnabled:true)
f32 collisionFloor{0.0f};
// Restitution: 0 = particles stop dead on the floor, 1 = a full elastic bounce.
- ES_PROPERTY(min=0, max=1, category=Collision)
+ ES_PROPERTY(min=0, max=1, category=Collision, shown_when=collisionEnabled:true)
f32 collisionBounce{0.5f};
// Tangential friction applied on each bounce (0 = frictionless slide, 1 = stop
// horizontal motion).
- ES_PROPERTY(min=0, max=1, category=Collision)
+ ES_PROPERTY(min=0, max=1, category=Collision, shown_when=collisionEnabled:true)
f32 collisionFriction{0.1f};
// Fraction of a particle's remaining life burned on each bounce (0 = none, 1 =
// dies on first contact) — fades splashes/sparks out as they settle.
- ES_PROPERTY(min=0, max=1, category=Collision)
+ ES_PROPERTY(min=0, max=1, category=Collision, shown_when=collisionEnabled:true)
f32 collisionLifetimeLoss{0.0f};
ParticleEmitter() = default;
diff --git a/src/esengine/ecs/components/TilemapLayer.hpp b/src/esengine/ecs/components/TilemapLayer.hpp
index 4f5f7207c..b66f7e924 100644
--- a/src/esengine/ecs/components/TilemapLayer.hpp
+++ b/src/esengine/ecs/components/TilemapLayer.hpp
@@ -53,13 +53,16 @@ struct TilemapLayer {
ES_PROPERTY(enum=TilemapOrientation, tooltip="Grid layout: orthogonal, isometric, staggered, or hexagonal.")
u8 orientation{0};
- ES_PROPERTY(min=0, step=1, tooltip="Hexagonal side length in px (0 = a regular pointy hex = tileHeight/2). Ignored unless orientation is Hexagonal.")
+ ES_PROPERTY(min=0, step=1, shown_when=orientation:Hexagonal,
+ tooltip="Hexagonal side length in px (0 = a regular pointy hex = tileHeight/2). Ignored unless orientation is Hexagonal.")
f32 hexSideLength{0.0f};
- ES_PROPERTY(enum=TilemapStaggerAxis, tooltip="Stagger axis (staggered/hex): Y shifts rows, X shifts columns.")
+ ES_PROPERTY(enum=TilemapStaggerAxis, shown_when=orientation:Staggered|Hexagonal,
+ tooltip="Stagger axis (staggered/hex): Y shifts rows, X shifts columns.")
u8 staggerAxis{0};
- ES_PROPERTY(enum=TilemapStaggerIndex, tooltip="Which lines carry the half-cell shift (staggered/hex).")
+ ES_PROPERTY(enum=TilemapStaggerIndex, shown_when=orientation:Staggered|Hexagonal,
+ tooltip="Which lines carry the half-cell shift (staggered/hex).")
u8 staggerIndex{0};
ES_PROPERTY()
diff --git a/tools/eht/generators/metadata.py b/tools/eht/generators/metadata.py
index c2c1cc404..5f2d8b5b8 100644
--- a/tools/eht/generators/metadata.py
+++ b/tools/eht/generators/metadata.py
@@ -115,10 +115,51 @@ class MetadataGenerator:
entries.append(('bitmask', '{ source: ' + json.dumps(a['bitmask_source'], ensure_ascii=False) + ' }'))
if 'normalized_of' in a:
entries.append(('normalizedOf', json.dumps(a['normalized_of'], ensure_ascii=False)))
+ if 'shown_when' in a:
+ entries.append(('shownWhen', self._shown_when(comp, prop, a['shown_when'])))
if entries:
out.append((prop.name, entries))
return out
+ def _shown_when(self, comp: Component, prop, raw: str) -> str:
+ """`shown_when=<field>:<State>|<State>` as `{ field, values: [n, ...] }`.
+
+ The states are resolved HERE, against the discriminator's own enum, because
+ this is where the enums are: the rule ships the numbers the data stores, and
+ reordering the enum moves the rule with it. A state that is not a member of
+ that enum is an error and not a 0 — a rule aimed at the wrong value hides a
+ field in the state it belongs to, which reads as the field having vanished.
+ """
+ loc = f'{comp.name}.{prop.name}'
+ field, _, states = raw.partition(':')
+ sibling = next((p for p in comp.properties if p.name == field), None)
+ if sibling is None:
+ raise ValueError(f"{loc}: shown_when reads '{field}', which is not a field here")
+ t = self.types.clean_type(sibling.cpp_type)
+ enum_name = t if self.types.is_enum(t) else sibling.annotations.get('enum')
+ members = self.types.get_enum_values(enum_name) if enum_name else []
+ values: List[int] = []
+ for state in states.split('|'):
+ state = state.strip()
+ if members:
+ if state not in members:
+ raise ValueError(
+ f"{loc}: shown_when names '{state}', which {enum_name} has no member of"
+ )
+ values.append(members.index(state))
+ elif t == 'bool':
+ if state not in ('true', 'false'):
+ raise ValueError(
+ f"{loc}: shown_when on the bool '{field}' takes true or false, not '{state}'"
+ )
+ values.append(1 if state == 'true' else 0)
+ else:
+ raise ValueError(
+ f"{loc}: shown_when reads '{field}', which is {t} — a state is an enum"
+ ' member or a bool'
+ )
+ return '{ field: ' + json.dumps(field) + ', values: [' + ', '.join(map(str, values)) + '] }'
+
def _get_editor_defaults(self, comp: Component) -> List[Tuple[str, str]]:
"""Collect `editor_default=` creation overrides as [(field, tsLiteral)].
diff --git a/tools/eht/parser.py b/tools/eht/parser.py
index d27a7020d..75357ce39 100644
--- a/tools/eht/parser.py
+++ b/tools/eht/parser.py
@@ -63,6 +63,12 @@ class CppParser:
# Same value grammar as a C++ member initializer: number, true/false,
# Enum::Member, or a braced vector `{100, 100}`.
'editor_default',
+ # `shown_when=<field>:<Name>|<Name>` scopes a field to the states of a sibling
+ # discriminator it means anything in — Light2D.radius to Point and Spot, a
+ # trail's tuning to trailEnabled:true. The states are named, never numbered,
+ # and resolved against that field's own enum when the metadata is generated,
+ # so reordering the enum moves every rule with it.
+ 'shown_when',
# `normalized_of=<sibling>` marks this field a FRACTION of that sibling's
# value (Sprite.pivot is a fraction of Sprite.size), so the editor can
# offer a pixel view of it. The stored value stays the fraction — the
@@ -248,15 +254,30 @@ class CppParser:
def _validate_component_refs(self, component: Component, filepath: Path) -> None:
"""Component-level checks that need the full field set: `invalidates=<field>`
must name a sibling property (else the generated setter side-effect would
- reference a non-existent member), and `normalized_of=<field>` must name a
+ reference a non-existent member), `normalized_of=<field>` must name a
sibling of the SAME type (the denominator is applied axis-wise, so a
- mismatched arity would divide an axis by nothing and read as 0)."""
+ mismatched arity would divide an axis by nothing and read as 0), and
+ `shown_when=<field>:...` must name a sibling to read its state from. What
+ those states MEAN is checked where the enums are, in the metadata generator."""
by_name = {p.name: p for p in component.properties}
for prop in component.properties:
loc = f"{filepath}:{component.name}.{prop.name}"
target = prop.annotations.get('invalidates')
if target is not None and target not in by_name:
self.errors.append(f"{loc}: invalidates='{target}' names no field on this component")
+ rule = prop.annotations.get('shown_when')
+ if rule is not None:
+ field, sep, states = rule.partition(':')
+ if not sep or not field.strip() or not states.strip():
+ self.errors.append(
+ f"{loc}: shown_when='{rule}' is not <field>:<State>|<State>"
+ )
+ elif field == prop.name:
+ self.errors.append(f"{loc}: shown_when='{rule}' reads the field itself")
+ elif field not in by_name:
+ self.errors.append(
+ f"{loc}: shown_when='{rule}' names no field on this component"
+ )
denom = prop.annotations.get('normalized_of')
if denom is None:
continue