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.

feat(reflection): ES_PROPERTY as the single source for field metadata (RC9-1)

esengine992d7c4f2b5c
diff --git a/sdk/src/component.generated.ts b/sdk/src/component.generated.ts
index b5819b81b..bdb792c19 100644
--- a/sdk/src/component.generated.ts
+++ b/sdk/src/component.generated.ts
@@ -5,6 +5,7 @@
*/
import type { AssetFieldType } from './scene';
+import type { FieldMeta } from './component';
/**
* Single-source-of-truth hash of the C++/TS boundary ABI (component
@@ -31,6 +32,7 @@ export interface ComponentMetaEntry {
entityFields: string[];
colorFields: string[];
animatableFields: string[];
+ fields?: Record<string, FieldMeta>;
}
export const COMPONENT_META: Record<string, ComponentMetaEntry> = {
@@ -49,6 +51,10 @@ export const COMPONENT_META: Record<string, ComponentMetaEntry> = {
entityFields: [],
colorFields: ['color'],
animatableFields: ['color.r', 'color.g', 'color.b', 'color.a'],
+ fields: {
+ fontSize: { min: 1 },
+ layer: { step: 1 },
+ },
},
BoxCollider: {
defaults: {
@@ -84,6 +90,16 @@ export const COMPONENT_META: Record<string, ComponentMetaEntry> = {
entityFields: [],
colorFields: [],
animatableFields: ['orthoSize'],
+ fields: {
+ projectionType: { tooltip: "Orthographic (2D) or Perspective projection." },
+ fov: { min: 1, max: 179, unit: "°" },
+ orthoSize: { min: 0, tooltip: "Half the visible height in world units (Orthographic)." },
+ 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." },
+ },
},
Canvas: {
defaults: {
@@ -97,6 +113,11 @@ export const COMPONENT_META: Record<string, ComponentMetaEntry> = {
entityFields: [],
colorFields: ['backgroundColor'],
animatableFields: [],
+ fields: {
+ pixelsPerUnit: { min: 1, tooltip: "Texture pixels mapped to one world unit." },
+ scaleMode: { tooltip: "How the canvas adapts the design resolution to the screen." },
+ matchWidthOrHeight: { min: 0, max: 1, slider: true, tooltip: "0 matches width, 1 matches height (Match mode only)." },
+ },
},
CapsuleCollider: {
defaults: {
@@ -183,6 +204,14 @@ export const COMPONENT_META: Record<string, ComponentMetaEntry> = {
entityFields: [],
colorFields: ['color'],
animatableFields: ['color.r', 'color.g', 'color.b', 'color.a', 'intensity', 'radius', 'innerAngle', 'outerAngle'],
+ fields: {
+ type: { 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)." },
+ direction: { tooltip: "Aim direction (Directional / Spot).", advanced: true },
+ innerAngle: { min: 0, max: 180, unit: "°", advanced: true },
+ outerAngle: { min: 0, max: 180, unit: "°", advanced: true },
+ },
},
Parent: {
defaults: {
@@ -241,6 +270,48 @@ export const COMPONENT_META: Record<string, ComponentMetaEntry> = {
entityFields: [],
colorFields: ['startColor', 'endColor'],
animatableFields: [],
+ fields: {
+ rate: { min: 0, category: "Emission" },
+ burstCount: { min: 0, step: 1, category: "Emission" },
+ burstInterval: { min: 0, category: "Emission" },
+ duration: { min: 0, category: "Emission" },
+ looping: { category: "Emission" },
+ playOnStart: { category: "Emission" },
+ maxParticles: { min: 1, step: 1, category: "Emission" },
+ lifetimeMin: { min: 0, category: "Lifetime" },
+ lifetimeMax: { min: 0, category: "Lifetime" },
+ shape: { category: "Shape" },
+ shapeRadius: { min: 0, category: "Shape" },
+ shapeSize: { category: "Shape" },
+ shapeAngle: { unit: "°", category: "Shape" },
+ speedMin: { category: "Velocity" },
+ speedMax: { category: "Velocity" },
+ angleSpreadMin: { unit: "°", category: "Velocity" },
+ angleSpreadMax: { unit: "°", category: "Velocity" },
+ startSizeMin: { min: 0, category: "Size" },
+ startSizeMax: { min: 0, category: "Size" },
+ endSizeMin: { min: 0, category: "Size" },
+ endSizeMax: { min: 0, category: "Size" },
+ sizeEasing: { category: "Size" },
+ startColor: { category: "Color" },
+ endColor: { category: "Color" },
+ colorEasing: { category: "Color" },
+ rotationMin: { unit: "°", category: "Rotation" },
+ rotationMax: { unit: "°", category: "Rotation" },
+ angularVelocityMin: { category: "Rotation" },
+ angularVelocityMax: { category: "Rotation" },
+ gravity: { category: "Velocity" },
+ damping: { min: 0, category: "Velocity" },
+ texture: { category: "Texture" },
+ spriteColumns: { min: 1, step: 1, category: "Texture" },
+ spriteRows: { min: 1, step: 1, category: "Texture" },
+ spriteFPS: { min: 0, category: "Texture" },
+ spriteLoop: { category: "Texture" },
+ blendMode: { category: "Rendering" },
+ layer: { step: 1, category: "Rendering", enumSource: "sortingLayers" },
+ material: { category: "Rendering" },
+ simulationSpace: { category: "Rendering" },
+ },
},
RigidBody: {
defaults: {
@@ -287,6 +358,10 @@ export const COMPONENT_META: Record<string, ComponentMetaEntry> = {
entityFields: [],
colorFields: ['color'],
animatableFields: [],
+ fields: {
+ cornerRadius: { min: 0 },
+ layer: { step: 1, enumSource: "sortingLayers" },
+ },
},
SpineAnimation: {
defaults: {
@@ -310,6 +385,11 @@ export const COMPONENT_META: Record<string, ComponentMetaEntry> = {
entityFields: [],
colorFields: ['color'],
animatableFields: [],
+ fields: {
+ timeScale: { min: 0 },
+ layer: { step: 1, enumSource: "sortingLayers" },
+ skeletonScale: { min: 0 },
+ },
},
Sprite: {
defaults: {
@@ -331,6 +411,16 @@ export const COMPONENT_META: Record<string, ComponentMetaEntry> = {
entityFields: [],
colorFields: ['color'],
animatableFields: ['color.r', 'color.g', 'color.b', 'color.a', 'size.x', 'size.y'],
+ fields: {
+ color: { tooltip: "Tint multiplied into the texture (white = unchanged)." },
+ pivot: { tooltip: "Anchor point (0–1) the sprite rotates and scales about.", advanced: true },
+ uvOffset: { advanced: true },
+ uvScale: { advanced: true },
+ layer: { step: 1, tooltip: "Sorting layer — controls draw order across sprites.", enumSource: "sortingLayers" },
+ tileSize: { advanced: true },
+ tileSpacing: { advanced: true },
+ material: { advanced: true },
+ },
},
StateMachine: {
defaults: {
@@ -371,6 +461,12 @@ export const COMPONENT_META: Record<string, ComponentMetaEntry> = {
entityFields: [],
colorFields: ['tintColor'],
animatableFields: ['tintColor.r', 'tintColor.g', 'tintColor.b', 'tintColor.a', 'opacity'],
+ fields: {
+ tilesetColumns: { min: 1, step: 1 },
+ tilesetRows: { min: 1, step: 1 },
+ renderLayer: { step: 1, enumSource: "sortingLayers" },
+ opacity: { min: 0, max: 1, slider: true, tooltip: "Layer transparency (0 = invisible, 1 = opaque)." },
+ },
},
Transform: {
defaults: {
@@ -385,6 +481,11 @@ export const COMPONENT_META: Record<string, ComponentMetaEntry> = {
entityFields: [],
colorFields: [],
animatableFields: ['position.x', 'position.y', 'position.z', 'rotation.z', 'scale.x', 'scale.y', 'scale.z'],
+ fields: {
+ position: { tooltip: "Local position in world units, relative to the parent." },
+ rotation: { tooltip: "Rotation about the Z axis, in degrees." },
+ scale: { tooltip: "Local scale per axis (1 = original size; negative flips)." },
+ },
},
UIInteraction: {
defaults: {
diff --git a/sdk/src/component.ts b/sdk/src/component.ts
index 977efb269..ac80850e4 100644
--- a/sdk/src/component.ts
+++ b/sdk/src/component.ts
@@ -338,6 +338,23 @@ export function getComponentFieldMeta(name: string): Readonly<Record<string, Fie
return getComponent(name)?.fieldMeta ?? {};
}
+/**
+ * Per-field merge of two FieldMeta maps: `override` wins key-by-key *within* a field
+ * (not whole-field replacement), so a builtin can author min/tooltip at the C++
+ * ES_PROPERTY site (→ `base`) and still add a runtime-only `enum`/`flags` override in
+ * TS without dropping the generated keys. See {@link defineBuiltin}.
+ */
+function mergeFieldMeta(
+ base: Record<string, FieldMeta>,
+ override: Record<string, FieldMeta>,
+): Record<string, FieldMeta> {
+ const out: Record<string, FieldMeta> = { ...base };
+ for (const k of Object.keys(override)) {
+ out[k] = { ...base[k], ...override[k] };
+ }
+ return out;
+}
+
function detectColorKeys(defaults: unknown): readonly string[] {
if (defaults === null || typeof defaults !== 'object') return [];
const keys: string[] = [];
@@ -392,7 +409,7 @@ export function defineBuiltin<T>(name: string, defaults: T, metadata?: Component
entityFields: metadata?.entityFields ?? meta?.entityFields ?? [],
colorKeys: meta?.colorFields ?? detectColorKeys(defaults),
animatableFields: meta?.animatableFields ?? [],
- fieldMeta: metadata?.fields ?? {},
+ fieldMeta: mergeFieldMeta(meta?.fields ?? {}, metadata?.fields ?? {}),
discoverAssets: metadata?.discoverAssets,
// Builtins declare transience via the defineBuiltin metadata arg for now;
// a C++-side ES_COMPONENT(transient) annotation can flow through
@@ -602,15 +619,13 @@ function metaDefaults<T>(name: string, overrides?: Partial<T>): T {
return (overrides ? { ...base, ...overrides } : { ...base }) as T;
}
+// Field presentation metadata (min/max/tooltip/category/…) is authored at the C++
+// ES_PROPERTY site and flows in via COMPONENT_META.fields (RC9-1). Only metadata that
+// can't be a static annotation — `enum`/`flags` built from a runtime TS constant, or a
+// TS-only field with no C++ backing — stays here as a per-field override (deep-merged
+// over the generated base by defineBuiltin).
export const Transform = defineBuiltin<TransformData>('Transform',
- metaDefaults<TransformData>('Transform'),
- {
- fields: {
- position: { tooltip: 'Local position in world units, relative to the parent.' },
- rotation: { tooltip: 'Rotation about the Z axis, in degrees.' },
- scale: { tooltip: 'Local scale per axis (1 = original size; negative flips).' },
- },
- }
+ metaDefaults<TransformData>('Transform')
);
export const LocalTransform = Transform;
export const WorldTransform = Transform;
@@ -618,44 +633,17 @@ export const WorldTransform = Transform;
export const Sprite = defineBuiltin<SpriteData>('Sprite',
metaDefaults<SpriteData>('Sprite', {
size: { x: DEFAULT_SPRITE_SIZE.x, y: DEFAULT_SPRITE_SIZE.y },
- }),
- {
- fields: {
- layer: { step: 1, enumSource: 'sortingLayers', tooltip: 'Sorting layer — controls draw order across sprites.' },
- color: { tooltip: 'Tint multiplied into the texture (white = unchanged).' },
- pivot: { advanced: true, tooltip: 'Anchor point (0–1) the sprite rotates and scales about.' },
- uvOffset: { advanced: true },
- uvScale: { advanced: true },
- tileSize: { advanced: true },
- tileSpacing: { advanced: true },
- material: { advanced: true },
- },
- }
+ })
);
export const ShapeRenderer = defineBuiltin<ShapeRendererData>('ShapeRenderer',
metaDefaults<ShapeRendererData>('ShapeRenderer'),
- {
- fields: {
- shapeType: { enum: enumOptions(ShapeType) },
- cornerRadius: { min: 0 },
- layer: { step: 1, enumSource: 'sortingLayers' },
- },
- }
+ { fields: { shapeType: { enum: enumOptions(ShapeType) } } }
);
export const Light2D = defineBuiltin<Light2DData>('Light2D',
metaDefaults<Light2DData>('Light2D'),
- {
- fields: {
- type: { enum: enumOptions(Light2DType), 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).' },
- direction: { advanced: true, tooltip: 'Aim direction (Directional / Spot).' },
- innerAngle: { min: 0, max: 180, unit: '°', advanced: true },
- outerAngle: { min: 0, max: 180, unit: '°', advanced: true },
- },
- }
+ { fields: { type: { enum: enumOptions(Light2DType) } } }
);
export const Camera = defineBuiltin<CameraData>('Camera',
@@ -668,15 +656,11 @@ export const Camera = defineBuiltin<CameraData>('Camera',
}),
{
fields: {
- projectionType: { enum: enumOptions(ProjectionType), tooltip: 'Orthographic (2D) or Perspective projection.' },
+ projectionType: { enum: enumOptions(ProjectionType) },
// A bitmask (ColorAndDepth = Color | Depth), so a multi-select, not a dropdown.
- clearFlags: { flags: [{ label: 'Color', value: 1 }, { label: 'Depth', value: 2 }], tooltip: 'Which buffers to clear before rendering this camera.' },
- fov: { min: 1, max: 179, unit: '°' },
- orthoSize: { min: 0, tooltip: 'Half the visible height in world units (Orthographic).' },
- nearPlane: { min: 0, advanced: true },
- farPlane: { min: 0, advanced: true },
- aspectRatio: { advanced: true },
- priority: { step: 1, advanced: true },
+ clearFlags: { flags: [{ label: 'Color', value: 1 }, { label: 'Depth', value: 2 }] },
+ // showFrustum is a TS-only editor field (no C++ Camera member), so its
+ // metadata can't come from an annotation.
showFrustum: { advanced: true },
},
}
@@ -690,13 +674,7 @@ export const Canvas = defineBuiltin<CanvasData>('Canvas',
}),
{
fields: {
- scaleMode: {
- enum: enumOptions(ScaleMode, ['FixedWidth', 'FixedHeight', 'Expand', 'Shrink', 'Match']),
- tooltip: 'How the canvas adapts the design resolution to the screen.',
- },
- // 0 = match width, 1 = match height (only meaningful in the Match mode).
- matchWidthOrHeight: { min: 0, max: 1, slider: true, tooltip: '0 matches width, 1 matches height (Match mode only).' },
- pixelsPerUnit: { min: 1, tooltip: 'Texture pixels mapped to one world unit.' },
+ scaleMode: { enum: enumOptions(ScaleMode, ['FixedWidth', 'FixedHeight', 'Expand', 'Shrink', 'Match']) },
},
}
);
@@ -714,31 +692,15 @@ export const Children = defineBuiltin<ChildrenData>('Children',
);
export const BitmapText = defineBuiltin<BitmapTextData>('BitmapText',
- metaDefaults<BitmapTextData>('BitmapText'),
- { fields: { fontSize: { min: 1 }, layer: { step: 1 } } }
+ metaDefaults<BitmapTextData>('BitmapText')
);
export const SpineAnimation = defineBuiltin<SpineAnimationData>('SpineAnimation',
- metaDefaults<SpineAnimationData>('SpineAnimation'),
- {
- fields: {
- timeScale: { min: 0 },
- skeletonScale: { min: 0 },
- layer: { step: 1, enumSource: 'sortingLayers' },
- },
- }
+ metaDefaults<SpineAnimationData>('SpineAnimation')
);
export const TilemapLayer = defineBuiltin<TilemapLayerData>('TilemapLayer',
- metaDefaults<TilemapLayerData>('TilemapLayer'),
- {
- fields: {
- opacity: { min: 0, max: 1, slider: true, tooltip: 'Layer transparency (0 = invisible, 1 = opaque).' },
- tilesetColumns: { min: 1, step: 1 },
- tilesetRows: { min: 1, step: 1 },
- renderLayer: { step: 1, enumSource: 'sortingLayers' },
- },
- }
+ metaDefaults<TilemapLayerData>('TilemapLayer')
);
// =============================================================================
@@ -833,50 +795,18 @@ export interface ParticleEmitterData {
export const ParticleEmitter = defineBuiltin<ParticleEmitterData>('ParticleEmitter',
metaDefaults<ParticleEmitterData>('ParticleEmitter', { colorGradient: { stops: [] }, sizeCurve: { keys: [] } }),
{
- // A large component — organized into UE-style property categories.
+ // Field categories + min/step/unit are authored at the C++ ES_PROPERTY site
+ // (→ COMPONENT_META.fields). Only what an annotation can't express stays here:
+ // enums built from runtime TS constants, and the two TS-only editor fields
+ // (sizeCurve / colorGradient have no C++ member, so their metadata lives here).
fields: {
- rate: { min: 0, category: 'Emission' },
- maxParticles: { min: 1, step: 1, category: 'Emission' },
- duration: { min: 0, category: 'Emission' },
- looping: { category: 'Emission' },
- playOnStart: { category: 'Emission' },
- burstCount: { min: 0, step: 1, category: 'Emission' },
- burstInterval: { min: 0, category: 'Emission' },
- lifetimeMin: { min: 0, category: 'Lifetime' },
- lifetimeMax: { min: 0, category: 'Lifetime' },
- shape: { enum: enumOptions(EmitterShape), category: 'Shape' },
- shapeRadius: { min: 0, category: 'Shape' },
- shapeSize: { category: 'Shape' },
- shapeAngle: { unit: '°', category: 'Shape' },
- speedMin: { category: 'Velocity' },
- speedMax: { category: 'Velocity' },
- angleSpreadMin: { unit: '°', category: 'Velocity' },
- angleSpreadMax: { unit: '°', category: 'Velocity' },
- gravity: { category: 'Velocity' },
- damping: { min: 0, category: 'Velocity' },
+ shape: { enum: enumOptions(EmitterShape) },
+ sizeEasing: { enum: enumOptions(ParticleEasing) },
+ colorEasing: { enum: enumOptions(ParticleEasing) },
+ blendMode: { enum: enumOptions(BlendMode) },
+ simulationSpace: { enum: enumOptions(SimulationSpace) },
sizeCurve: { curve: true, category: 'Size' },
- startSizeMin: { min: 0, category: 'Size' },
- startSizeMax: { min: 0, category: 'Size' },
- endSizeMin: { min: 0, category: 'Size' },
- endSizeMax: { min: 0, category: 'Size' },
- sizeEasing: { enum: enumOptions(ParticleEasing), category: 'Size' },
colorGradient: { gradient: true, category: 'Color' },
- startColor: { category: 'Color' },
- endColor: { category: 'Color' },
- colorEasing: { enum: enumOptions(ParticleEasing), category: 'Color' },
- rotationMin: { unit: '°', category: 'Rotation' },
- rotationMax: { unit: '°', category: 'Rotation' },
- angularVelocityMin: { category: 'Rotation' },
- angularVelocityMax: { category: 'Rotation' },
- texture: { category: 'Texture' },
- spriteColumns: { min: 1, step: 1, category: 'Texture' },
- spriteRows: { min: 1, step: 1, category: 'Texture' },
- spriteFPS: { min: 0, category: 'Texture' },
- spriteLoop: { category: 'Texture' },
- blendMode: { enum: enumOptions(BlendMode), category: 'Rendering' },
- layer: { step: 1, category: 'Rendering', enumSource: 'sortingLayers' },
- material: { category: 'Rendering' },
- simulationSpace: { enum: enumOptions(SimulationSpace), category: 'Rendering' },
},
}
);
diff --git a/sdk/tests/__snapshots__/component-fieldmeta-golden.test.ts.snap b/sdk/tests/__snapshots__/component-fieldmeta-golden.test.ts.snap
new file mode 100644
index 000000000..54175129c
--- /dev/null
+++ b/sdk/tests/__snapshots__/component-fieldmeta-golden.test.ts.snap
@@ -0,0 +1,493 @@
+// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
+
+exports[`builtin FieldMeta (RC9-1 equivalence gate) > matches the golden snapshot of every builtin with declared field metadata 1`] = `
+{
+ "BitmapText": {
+ "fontSize": {
+ "min": 1,
+ },
+ "layer": {
+ "step": 1,
+ },
+ },
+ "Camera": {
+ "aspectRatio": {
+ "advanced": true,
+ },
+ "clearFlags": {
+ "flags": [
+ {
+ "label": "Color",
+ "value": 1,
+ },
+ {
+ "label": "Depth",
+ "value": 2,
+ },
+ ],
+ "tooltip": "Which buffers to clear before rendering this camera.",
+ },
+ "farPlane": {
+ "advanced": true,
+ "min": 0,
+ },
+ "fov": {
+ "max": 179,
+ "min": 1,
+ "unit": "°",
+ },
+ "nearPlane": {
+ "advanced": true,
+ "min": 0,
+ },
+ "orthoSize": {
+ "min": 0,
+ "tooltip": "Half the visible height in world units (Orthographic).",
+ },
+ "priority": {
+ "advanced": true,
+ "step": 1,
+ },
+ "projectionType": {
+ "enum": [
+ {
+ "label": "Perspective",
+ "value": 0,
+ },
+ {
+ "label": "Orthographic",
+ "value": 1,
+ },
+ ],
+ "tooltip": "Orthographic (2D) or Perspective projection.",
+ },
+ "showFrustum": {
+ "advanced": true,
+ },
+ },
+ "Canvas": {
+ "matchWidthOrHeight": {
+ "max": 1,
+ "min": 0,
+ "slider": true,
+ "tooltip": "0 matches width, 1 matches height (Match mode only).",
+ },
+ "pixelsPerUnit": {
+ "min": 1,
+ "tooltip": "Texture pixels mapped to one world unit.",
+ },
+ "scaleMode": {
+ "enum": [
+ {
+ "label": "FixedWidth",
+ "value": 0,
+ },
+ {
+ "label": "FixedHeight",
+ "value": 1,
+ },
+ {
+ "label": "Expand",
+ "value": 2,
+ },
+ {
+ "label": "Shrink",
+ "value": 3,
+ },
+ {
+ "label": "Match",
+ "value": 4,
+ },
+ ],
+ "tooltip": "How the canvas adapts the design resolution to the screen.",
+ },
+ },
+ "Light2D": {
+ "direction": {
+ "advanced": true,
+ "tooltip": "Aim direction (Directional / Spot).",
+ },
+ "innerAngle": {
+ "advanced": true,
+ "max": 180,
+ "min": 0,
+ "unit": "°",
+ },
+ "intensity": {
+ "min": 0,
+ "tooltip": "Brightness multiplier of the light.",
+ },
+ "outerAngle": {
+ "advanced": true,
+ "max": 180,
+ "min": 0,
+ "unit": "°",
+ },
+ "radius": {
+ "min": 0,
+ "tooltip": "Falloff reach in world units (Point / Spot).",
+ },
+ "type": {
+ "enum": [
+ {
+ "label": "Point",
+ "value": 0,
+ },
+ {
+ "label": "Directional",
+ "value": 1,
+ },
+ {
+ "label": "Ambient",
+ "value": 2,
+ },
+ {
+ "label": "Spot",
+ "value": 3,
+ },
+ ],
+ "tooltip": "Point, Directional, Ambient, or Spot.",
+ },
+ },
+ "ParticleEmitter": {
+ "angleSpreadMax": {
+ "category": "Velocity",
+ "unit": "°",
+ },
+ "angleSpreadMin": {
+ "category": "Velocity",
+ "unit": "°",
+ },
+ "angularVelocityMax": {
+ "category": "Rotation",
+ },
+ "angularVelocityMin": {
+ "category": "Rotation",
+ },
+ "blendMode": {
+ "category": "Rendering",
+ "enum": [
+ {
+ "label": "Normal",
+ "value": 0,
+ },
+ {
+ "label": "Additive",
+ "value": 1,
+ },
+ {
+ "label": "Multiply",
+ "value": 2,
+ },
+ {
+ "label": "Screen",
+ "value": 3,
+ },
+ {
+ "label": "PremultipliedAlpha",
+ "value": 4,
+ },
+ ],
+ },
+ "burstCount": {
+ "category": "Emission",
+ "min": 0,
+ "step": 1,
+ },
+ "burstInterval": {
+ "category": "Emission",
+ "min": 0,
+ },
+ "colorEasing": {
+ "category": "Color",
+ "enum": [
+ {
+ "label": "Linear",
+ "value": 0,
+ },
+ {
+ "label": "EaseIn",
+ "value": 1,
+ },
+ {
+ "label": "EaseOut",
+ "value": 2,
+ },
+ {
+ "label": "EaseInOut",
+ "value": 3,
+ },
+ ],
+ },
+ "colorGradient": {
+ "category": "Color",
+ "gradient": true,
+ },
+ "damping": {
+ "category": "Velocity",
+ "min": 0,
+ },
+ "duration": {
+ "category": "Emission",
+ "min": 0,
+ },
+ "endColor": {
+ "category": "Color",
+ },
+ "endSizeMax": {
+ "category": "Size",
+ "min": 0,
+ },
+ "endSizeMin": {
+ "category": "Size",
+ "min": 0,
+ },
+ "gravity": {
+ "category": "Velocity",
+ },
+ "layer": {
+ "category": "Rendering",
+ "enumSource": "sortingLayers",
+ "step": 1,
+ },
+ "lifetimeMax": {
+ "category": "Lifetime",
+ "min": 0,
+ },
+ "lifetimeMin": {
+ "category": "Lifetime",
+ "min": 0,
+ },
+ "looping": {
+ "category": "Emission",
+ },
+ "material": {
+ "category": "Rendering",
+ },
+ "maxParticles": {
+ "category": "Emission",
+ "min": 1,
+ "step": 1,
+ },
+ "playOnStart": {
+ "category": "Emission",
+ },
+ "rate": {
+ "category": "Emission",
+ "min": 0,
+ },
+ "rotationMax": {
+ "category": "Rotation",
+ "unit": "°",
+ },
+ "rotationMin": {
+ "category": "Rotation",
+ "unit": "°",
+ },
+ "shape": {
+ "category": "Shape",
+ "enum": [
+ {
+ "label": "Point",
+ "value": 0,
+ },
+ {
+ "label": "Circle",
+ "value": 1,
+ },
+ {
+ "label": "Rectangle",
+ "value": 2,
+ },
+ {
+ "label": "Cone",
+ "value": 3,
+ },
+ ],
+ },
+ "shapeAngle": {
+ "category": "Shape",
+ "unit": "°",
+ },
+ "shapeRadius": {
+ "category": "Shape",
+ "min": 0,
+ },
+ "shapeSize": {
+ "category": "Shape",
+ },
+ "simulationSpace": {
+ "category": "Rendering",
+ "enum": [
+ {
+ "label": "World",
+ "value": 0,
+ },
+ {
+ "label": "Local",
+ "value": 1,
+ },
+ ],
+ },
+ "sizeCurve": {
+ "category": "Size",
+ "curve": true,
+ },
+ "sizeEasing": {
+ "category": "Size",
+ "enum": [
+ {
+ "label": "Linear",
+ "value": 0,
+ },
+ {
+ "label": "EaseIn",
+ "value": 1,
+ },
+ {
+ "label": "EaseOut",
+ "value": 2,
+ },
+ {
+ "label": "EaseInOut",
+ "value": 3,
+ },
+ ],
+ },
+ "speedMax": {
+ "category": "Velocity",
+ },
+ "speedMin": {
+ "category": "Velocity",
+ },
+ "spriteColumns": {
+ "category": "Texture",
+ "min": 1,
+ "step": 1,
+ },
+ "spriteFPS": {
+ "category": "Texture",
+ "min": 0,
+ },
+ "spriteLoop": {
+ "category": "Texture",
+ },
+ "spriteRows": {
+ "category": "Texture",
+ "min": 1,
+ "step": 1,
+ },
+ "startColor": {
+ "category": "Color",
+ },
+ "startSizeMax": {
+ "category": "Size",
+ "min": 0,
+ },
+ "startSizeMin": {
+ "category": "Size",
+ "min": 0,
+ },
+ "texture": {
+ "category": "Texture",
+ },
+ },
+ "ShapeRenderer": {
+ "cornerRadius": {
+ "min": 0,
+ },
+ "layer": {
+ "enumSource": "sortingLayers",
+ "step": 1,
+ },
+ "shapeType": {
+ "enum": [
+ {
+ "label": "Circle",
+ "value": 0,
+ },
+ {
+ "label": "Capsule",
+ "value": 1,
+ },
+ {
+ "label": "RoundedRect",
+ "value": 2,
+ },
+ ],
+ },
+ },
+ "SpineAnimation": {
+ "layer": {
+ "enumSource": "sortingLayers",
+ "step": 1,
+ },
+ "skeletonScale": {
+ "min": 0,
+ },
+ "timeScale": {
+ "min": 0,
+ },
+ },
+ "Sprite": {
+ "color": {
+ "tooltip": "Tint multiplied into the texture (white = unchanged).",
+ },
+ "layer": {
+ "enumSource": "sortingLayers",
+ "step": 1,
+ "tooltip": "Sorting layer — controls draw order across sprites.",
+ },
+ "material": {
+ "advanced": true,
+ },
+ "pivot": {
+ "advanced": true,
+ "tooltip": "Anchor point (0–1) the sprite rotates and scales about.",
+ },
+ "tileSize": {
+ "advanced": true,
+ },
+ "tileSpacing": {
+ "advanced": true,
+ },
+ "uvOffset": {
+ "advanced": true,
+ },
+ "uvScale": {
+ "advanced": true,
+ },
+ },
+ "TilemapLayer": {
+ "opacity": {
+ "max": 1,
+ "min": 0,
+ "slider": true,
+ "tooltip": "Layer transparency (0 = invisible, 1 = opaque).",
+ },
+ "renderLayer": {
+ "enumSource": "sortingLayers",
+ "step": 1,
+ },
+ "tilesetColumns": {
+ "min": 1,
+ "step": 1,
+ },
+ "tilesetRows": {
+ "min": 1,
+ "step": 1,
+ },
+ },
+ "Transform": {
+ "position": {
+ "tooltip": "Local position in world units, relative to the parent.",
+ },
+ "rotation": {
+ "tooltip": "Rotation about the Z axis, in degrees.",
+ },
+ "scale": {
+ "tooltip": "Local scale per axis (1 = original size; negative flips).",
+ },
+ },
+}
+`;
diff --git a/sdk/tests/component-fieldmeta-golden.test.ts b/sdk/tests/component-fieldmeta-golden.test.ts
new file mode 100644
index 000000000..5af0c3198
--- /dev/null
+++ b/sdk/tests/component-fieldmeta-golden.test.ts
@@ -0,0 +1,21 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+import { describe, it, expect } from 'vitest';
+import { getAllRegisteredComponents, getComponentFieldMeta } from '../src/component';
+
+// Equivalence gate for RC9-1 (rich reflection metadata, single authoring source).
+// P2 moves the authority for builtin field presentation metadata from the
+// hand-written component.ts overlay into generated COMPONENT_META.fields. That
+// migration changes the *source* of these values, never the values themselves —
+// this snapshot fails if any field's resolved metadata drifts during the move.
+describe('builtin FieldMeta (RC9-1 equivalence gate)', () => {
+ it('matches the golden snapshot of every builtin with declared field metadata', () => {
+ const names = [...getAllRegisteredComponents().keys()].sort();
+ const golden: Record<string, Readonly<Record<string, unknown>>> = {};
+ for (const name of names) {
+ const meta = getComponentFieldMeta(name);
+ if (Object.keys(meta).length > 0) golden[name] = meta;
+ }
+ expect(golden).toMatchSnapshot();
+ });
+});
diff --git a/src/esengine/bindings/EditorAPI.generated.cpp b/src/esengine/bindings/EditorAPI.generated.cpp
index a91cc292a..c2096187c 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 517314ab9b2a2e13
+ * @schema_hash d7fda004452fec53
*/
-#define ES_EDITOR_API_SCHEMA_HASH "517314ab9b2a2e13"
+#define ES_EDITOR_API_SCHEMA_HASH "d7fda004452fec53"
#include <emscripten/bind.h>
#include <string>
diff --git a/src/esengine/core/Reflection.hpp b/src/esengine/core/Reflection.hpp
index d16516a04..b536229be 100644
--- a/src/esengine/core/Reflection.hpp
+++ b/src/esengine/core/Reflection.hpp
@@ -43,17 +43,42 @@
* JavaScript/TypeScript with automatic getter/setter generation.
* Only works inside ES_COMPONENT() marked types.
*
- * Supports optional metadata annotations parsed by EHT:
- * - asset=<type> : marks field as asset reference (texture, material, font, audio, etc.)
- * - animatable : marks field as animatable via timeline
- * - entity_ref : marks field as entity reference (for ID remapping)
+ * This is the single authoring site for a field's editor/serialization
+ * metadata (RC9-1): the value lives in the struct, the presentation policy
+ * lives in the annotation, and EHT generates both the TS metadata and the
+ * C++ editor schema from it. Vocabulary parsed/validated by EHT:
+ *
+ * Semantics (flags):
+ * - asset=<type> : asset reference (texture, material, font, audio, spine_skeleton, spine_atlas)
+ * - animatable : keyframeable via the Sequencer/timeline
+ * - anim_override : field may be tween-driven; layout must not clobber it
* - anim_flag=<flag> : animation side-effect flag (e.g. ANIM_POS_X on UINode)
+ * - entity_ref : entity reference (remapped on scene load / instancing)
+ * - readonly : not editable in the inspector
+ *
+ * Editor presentation:
+ * - min=<n> / max=<n> / step=<n> : numeric range and scrub granularity
+ * - slider : render as a slider (requires both min= and max=)
+ * - unit=<s> : unit suffix shown after the value (e.g. °, px, %)
+ * - label=<s> / tooltip=<s> : human label / hover text
+ * - category=<s> : inspector group header
+ * - advanced : tuck behind an "advanced" fold
+ * - enum_source=<name> / bitmask_source=<name> : editor-resolved option/label source
+ *
+ * Serialization / runtime policy:
+ * - invalidates=<field> : after an editor set, flip <field> so the owning
+ * system re-runs its load path next tick
+ * - skip_serialize : omit from scene serialization (runtime-only state)
+ * - replicated : eligible for network replication (RC11; reserved)
+ *
+ * Malformed *known* metadata (a non-numeric min=, slider without a range,
+ * invalidates= naming no field) is a hard EHT error, not a silent drop.
*
* Examples:
* ES_PROPERTY(asset=texture)
- * ES_PROPERTY(animatable)
* ES_PROPERTY(animatable, anim_flag=ANIM_POS_X)
- * ES_PROPERTY(entity_ref)
+ * ES_PROPERTY(min=0, max=180, unit="°", advanced, category="Spot")
+ * ES_PROPERTY(invalidates=needsReload)
*/
#define ES_PROPERTY(...)
diff --git a/src/esengine/ecs/components/BitmapText.hpp b/src/esengine/ecs/components/BitmapText.hpp
index 40fe4afaa..dfba20655 100644
--- a/src/esengine/ecs/components/BitmapText.hpp
+++ b/src/esengine/ecs/components/BitmapText.hpp
@@ -26,7 +26,7 @@ struct BitmapText {
ES_PROPERTY(animatable)
glm::vec4 color{1.0f};
- ES_PROPERTY()
+ ES_PROPERTY(min=1)
f32 fontSize{1.0f};
ES_PROPERTY()
@@ -35,7 +35,7 @@ struct BitmapText {
ES_PROPERTY()
f32 spacing{0.0f};
- ES_PROPERTY()
+ ES_PROPERTY(step=1)
i32 layer{0};
ES_PROPERTY(asset = font)
diff --git a/src/esengine/ecs/components/Camera.hpp b/src/esengine/ecs/components/Camera.hpp
index a06223548..6ffe79042 100644
--- a/src/esengine/ecs/components/Camera.hpp
+++ b/src/esengine/ecs/components/Camera.hpp
@@ -69,27 +69,27 @@ enum class ClearFlags : u8 {
ES_COMPONENT()
struct Camera {
/** @brief Projection type */
- ES_PROPERTY()
+ ES_PROPERTY(tooltip="Orthographic (2D) or Perspective projection.")
ProjectionType projectionType{ProjectionType::Perspective};
/** @brief Field of view in degrees (perspective only) */
- ES_PROPERTY()
+ ES_PROPERTY(min=1, max=179, unit="°")
f32 fov{60.0f};
/** @brief Orthographic size (half-height in world units) */
- ES_PROPERTY(animatable)
+ ES_PROPERTY(animatable, min=0, tooltip="Half the visible height in world units (Orthographic).")
f32 orthoSize{5.0f};
/** @brief Near clipping plane distance */
- ES_PROPERTY()
+ ES_PROPERTY(min=0, advanced)
f32 nearPlane{0.1f};
/** @brief Far clipping plane distance */
- ES_PROPERTY()
+ ES_PROPERTY(min=0, advanced)
f32 farPlane{1000.0f};
/** @brief Aspect ratio (width / height), 0 = auto from viewport */
- ES_PROPERTY()
+ ES_PROPERTY(advanced)
f32 aspectRatio{0.0f};
/** @brief Whether this is the active camera */
@@ -97,14 +97,14 @@ struct Camera {
bool isActive{false};
/** @brief Priority for determining active camera (higher = preferred) */
- ES_PROPERTY()
+ ES_PROPERTY(step=1, advanced)
i32 priority{0};
/** @brief Viewport rectangle (x, y, width, height) in normalized coords */
ES_PROPERTY()
glm::vec4 viewport{0.0f, 0.0f, 1.0f, 1.0f};
- ES_PROPERTY()
+ ES_PROPERTY(tooltip="Which buffers to clear before rendering this camera.")
ClearFlags clearFlags{ClearFlags::ColorAndDepth};
Camera() = default;
diff --git a/src/esengine/ecs/components/Canvas.hpp b/src/esengine/ecs/components/Canvas.hpp
index 462afdf1c..ea3aebb82 100644
--- a/src/esengine/ecs/components/Canvas.hpp
+++ b/src/esengine/ecs/components/Canvas.hpp
@@ -72,15 +72,15 @@ struct Canvas {
glm::uvec2 designResolution{1920, 1080};
/** @brief Pixels per world unit (e.g., 100 means 100px = 1 unit) */
- ES_PROPERTY()
+ ES_PROPERTY(min=1, tooltip="Texture pixels mapped to one world unit.")
f32 pixelsPerUnit{100.0f};
/** @brief Scaling mode for different screen resolutions */
- ES_PROPERTY()
+ ES_PROPERTY(tooltip="How the canvas adapts the design resolution to the screen.")
CanvasScaleMode scaleMode{CanvasScaleMode::FixedHeight};
/** @brief Match factor for Match scale mode (0 = width, 1 = height) */
- ES_PROPERTY()
+ ES_PROPERTY(min=0, max=1, slider, tooltip="0 matches width, 1 matches height (Match mode only).")
f32 matchWidthOrHeight{0.5f};
/** @brief Background color for letterbox/pillarbox areas */
diff --git a/src/esengine/ecs/components/Light2D.hpp b/src/esengine/ecs/components/Light2D.hpp
index 29d73d71b..059ba1f92 100644
--- a/src/esengine/ecs/components/Light2D.hpp
+++ b/src/esengine/ecs/components/Light2D.hpp
@@ -47,7 +47,7 @@ enum class Light2DType : i32 {
ES_COMPONENT()
struct Light2D {
/** @brief Light kind: 0 = Point, 1 = Directional, 2 = Ambient (see Light2DType). */
- ES_PROPERTY()
+ ES_PROPERTY(tooltip="Point, Directional, Ambient, or Spot.")
i32 type{0};
/** @brief Light color, multiplied by intensity. RGBA for editor color-picker consistency
@@ -57,24 +57,24 @@ struct Light2D {
glm::vec4 color{1.0f, 1.0f, 1.0f, 1.0f};
/** @brief Light strength multiplier. */
- ES_PROPERTY(animatable)
+ ES_PROPERTY(animatable, min=0, tooltip="Brightness multiplier of the light.")
f32 intensity{1.0f};
/** @brief Point/Spot falloff radius in world units (ignored by Directional/Ambient). */
- ES_PROPERTY(animatable)
+ ES_PROPERTY(animatable, min=0, tooltip="Falloff reach in world units (Point / Spot).")
f32 radius{200.0f};
/** @brief Direction in the 2D plane: Directional light direction, or Spot cone axis
* ({0,0} = straight at the screen / cone aims down). Ignored by Point/Ambient. */
- ES_PROPERTY()
+ ES_PROPERTY(advanced, tooltip="Aim direction (Directional / Spot).")
glm::vec2 direction{0.0f, 0.0f};
/** @brief Spot inner cone angle in degrees (full angle; fully lit inside). */
- ES_PROPERTY(animatable)
+ ES_PROPERTY(animatable, min=0, max=180, unit="°", advanced)
f32 innerAngle{30.0f};
/** @brief Spot outer cone angle in degrees (full angle; fades to dark by here). */
- ES_PROPERTY(animatable)
+ ES_PROPERTY(animatable, min=0, max=180, unit="°", advanced)
f32 outerAngle{45.0f};
/** @brief Disabled lights are skipped during collection. */
diff --git a/src/esengine/ecs/components/ParticleEmitter.hpp b/src/esengine/ecs/components/ParticleEmitter.hpp
index f42917db8..e6c32fe4f 100644
--- a/src/esengine/ecs/components/ParticleEmitter.hpp
+++ b/src/esengine/ecs/components/ParticleEmitter.hpp
@@ -27,134 +27,134 @@ enum class SimulationSpace : i32 {
ES_COMPONENT()
struct ParticleEmitter {
// Emission
- ES_PROPERTY()
+ ES_PROPERTY(min=0, category=Emission)
f32 rate{10.0f};
- ES_PROPERTY()
+ ES_PROPERTY(min=0, step=1, category=Emission)
i32 burstCount{0};
- ES_PROPERTY()
+ ES_PROPERTY(min=0, category=Emission)
f32 burstInterval{1.0f};
- ES_PROPERTY()
+ ES_PROPERTY(min=0, category=Emission)
f32 duration{5.0f};
- ES_PROPERTY()
+ ES_PROPERTY(category=Emission)
bool looping{true};
- ES_PROPERTY()
+ ES_PROPERTY(category=Emission)
bool playOnStart{true};
- ES_PROPERTY()
+ ES_PROPERTY(min=1, step=1, category=Emission)
i32 maxParticles{1000};
// Lifetime
- ES_PROPERTY()
+ ES_PROPERTY(min=0, category=Lifetime)
f32 lifetimeMin{5.0f};
- ES_PROPERTY()
+ ES_PROPERTY(min=0, category=Lifetime)
f32 lifetimeMax{5.0f};
- // Shape
- ES_PROPERTY()
+ // Shape (shape kind enum stays a TS-side override — runtime enumOptions constant)
+ ES_PROPERTY(category=Shape)
i32 shape{static_cast<i32>(EmitterShape::Cone)};
- ES_PROPERTY()
+ ES_PROPERTY(min=0, category=Shape)
f32 shapeRadius{100.0f};
- ES_PROPERTY()
+ ES_PROPERTY(category=Shape)
glm::vec2 shapeSize{100.0f, 100.0f};
- ES_PROPERTY()
+ ES_PROPERTY(unit="°", category=Shape)
f32 shapeAngle{25.0f};
// Velocity
- ES_PROPERTY()
+ ES_PROPERTY(category=Velocity)
f32 speedMin{500.0f};
- ES_PROPERTY()
+ ES_PROPERTY(category=Velocity)
f32 speedMax{500.0f};
- ES_PROPERTY()
+ ES_PROPERTY(unit="°", category=Velocity)
f32 angleSpreadMin{0.0f};
- ES_PROPERTY()
+ ES_PROPERTY(unit="°", category=Velocity)
f32 angleSpreadMax{360.0f};
// Size
- ES_PROPERTY()
+ ES_PROPERTY(min=0, category=Size)
f32 startSizeMin{100.0f};
- ES_PROPERTY()
+ ES_PROPERTY(min=0, category=Size)
f32 startSizeMax{100.0f};
- ES_PROPERTY()
+ ES_PROPERTY(min=0, category=Size)
f32 endSizeMin{100.0f};
- ES_PROPERTY()
+ ES_PROPERTY(min=0, category=Size)
f32 endSizeMax{100.0f};
- ES_PROPERTY()
+ ES_PROPERTY(category=Size)
i32 sizeEasing{static_cast<i32>(particle::EasingType::Linear)};
// Color
- ES_PROPERTY()
+ ES_PROPERTY(category=Color)
glm::vec4 startColor{1.0f, 1.0f, 1.0f, 1.0f};
- ES_PROPERTY()
+ ES_PROPERTY(category=Color)
glm::vec4 endColor{1.0f, 1.0f, 1.0f, 0.0f};
- ES_PROPERTY()
+ ES_PROPERTY(category=Color)
i32 colorEasing{static_cast<i32>(particle::EasingType::Linear)};
// Rotation
- ES_PROPERTY()
+ ES_PROPERTY(unit="°", category=Rotation)
f32 rotationMin{0.0f};
- ES_PROPERTY()
+ ES_PROPERTY(unit="°", category=Rotation)
f32 rotationMax{0.0f};
- ES_PROPERTY()
+ ES_PROPERTY(category=Rotation)
f32 angularVelocityMin{0.0f};
- ES_PROPERTY()
+ ES_PROPERTY(category=Rotation)
f32 angularVelocityMax{0.0f};
- // Forces
- ES_PROPERTY()
+ // Forces (grouped under the Velocity category in the inspector)
+ ES_PROPERTY(category=Velocity)
glm::vec2 gravity{0.0f, 0.0f};
- ES_PROPERTY()
+ ES_PROPERTY(min=0, category=Velocity)
f32 damping{0.0f};
// Texture
- ES_PROPERTY(asset = texture)
+ ES_PROPERTY(asset = texture, category=Texture)
resource::TextureHandle texture;
- ES_PROPERTY()
+ ES_PROPERTY(min=1, step=1, category=Texture)
i32 spriteColumns{1};
- ES_PROPERTY()
+ ES_PROPERTY(min=1, step=1, category=Texture)
i32 spriteRows{1};
- ES_PROPERTY()
+ ES_PROPERTY(min=0, category=Texture)
f32 spriteFPS{10.0f};
- ES_PROPERTY()
+ ES_PROPERTY(category=Texture)
bool spriteLoop{true};
- // Rendering
- ES_PROPERTY()
+ // Rendering (blendMode/simulationSpace enums stay TS-side overrides)
+ ES_PROPERTY(category=Rendering)
i32 blendMode{1};
- ES_PROPERTY()
+ ES_PROPERTY(step=1, enum_source=sortingLayers, category=Rendering)
i32 layer{0};
- ES_PROPERTY(asset = material)
+ ES_PROPERTY(asset = material, category=Rendering)
u32 material{0};
// Space
- ES_PROPERTY()
+ ES_PROPERTY(category=Rendering)
i32 simulationSpace{static_cast<i32>(SimulationSpace::World)};
// State
diff --git a/src/esengine/ecs/components/ShapeRenderer.hpp b/src/esengine/ecs/components/ShapeRenderer.hpp
index 9d00f175f..d6850d172 100644
--- a/src/esengine/ecs/components/ShapeRenderer.hpp
+++ b/src/esengine/ecs/components/ShapeRenderer.hpp
@@ -19,10 +19,10 @@ struct ShapeRenderer {
ES_PROPERTY()
glm::vec2 size{100.0f, 100.0f};
- ES_PROPERTY()
+ ES_PROPERTY(min=0)
f32 cornerRadius{0.0f};
- ES_PROPERTY()
+ ES_PROPERTY(step=1, enum_source=sortingLayers)
i32 layer{0};
ES_PROPERTY()
diff --git a/src/esengine/ecs/components/SpineAnimation.hpp b/src/esengine/ecs/components/SpineAnimation.hpp
index 5d3e8cee5..7797ce2b4 100644
--- a/src/esengine/ecs/components/SpineAnimation.hpp
+++ b/src/esengine/ecs/components/SpineAnimation.hpp
@@ -65,7 +65,7 @@ struct SpineAnimation {
std::string animation;
/** @brief Animation playback speed multiplier */
- ES_PROPERTY()
+ ES_PROPERTY(min=0)
f32 timeScale{1.0f};
/** @brief Whether to loop the animation */
@@ -89,11 +89,11 @@ struct SpineAnimation {
glm::vec4 color{1.0f, 1.0f, 1.0f, 1.0f};
/** @brief Sorting layer (higher = rendered on top) */
- ES_PROPERTY()
+ ES_PROPERTY(step=1, enum_source=sortingLayers)
i32 layer{0};
/** @brief Skeleton scale factor */
- ES_PROPERTY()
+ ES_PROPERTY(min=0)
f32 skeletonScale{1.0f};
/** @brief Custom material ID (0 = use default batch shader) */
diff --git a/src/esengine/ecs/components/Sprite.hpp b/src/esengine/ecs/components/Sprite.hpp
index d0917d7d5..9c07e85a9 100644
--- a/src/esengine/ecs/components/Sprite.hpp
+++ b/src/esengine/ecs/components/Sprite.hpp
@@ -50,7 +50,7 @@ struct Sprite {
resource::TextureHandle texture;
/** @brief Color tint (RGBA, 0-1 range) */
- ES_PROPERTY(animatable)
+ ES_PROPERTY(animatable, tooltip="Tint multiplied into the texture (white = unchanged).")
glm::vec4 color{1.0f, 1.0f, 1.0f, 1.0f};
/** @brief Sprite size in world units */
@@ -58,19 +58,19 @@ struct Sprite {
glm::vec2 size{1.0f, 1.0f};
/** @brief Pivot point (0,0 = bottom-left, 0.5,0.5 = center, 1,1 = top-right) */
- ES_PROPERTY()
+ ES_PROPERTY(advanced, tooltip="Anchor point (0–1) the sprite rotates and scales about.")
glm::vec2 pivot{0.5f, 0.5f};
/** @brief UV coordinate offset for sprite sheets */
- ES_PROPERTY()
+ ES_PROPERTY(advanced)
glm::vec2 uvOffset{0.0f, 0.0f};
/** @brief UV coordinate scale for sprite sheets */
- ES_PROPERTY()
+ ES_PROPERTY(advanced)
glm::vec2 uvScale{1.0f, 1.0f};
/** @brief Sorting layer (higher = rendered on top) */
- ES_PROPERTY()
+ ES_PROPERTY(step=1, enum_source=sortingLayers, tooltip="Sorting layer — controls draw order across sprites.")
i32 layer{0};
/** @brief Flip sprite horizontally */
@@ -82,15 +82,15 @@ struct Sprite {
bool flipY{false};
/** @brief Tile size in world units for tiling mode ({0,0} = no tiling) */
- ES_PROPERTY()
+ ES_PROPERTY(advanced)
glm::vec2 tileSize{0.0f, 0.0f};
/** @brief Spacing between tiles in world units ({0,0} = seamless) */
- ES_PROPERTY()
+ ES_PROPERTY(advanced)
glm::vec2 tileSpacing{0.0f, 0.0f};
/** @brief Custom material ID (0 = use default batch shader) */
- ES_PROPERTY(asset = material)
+ ES_PROPERTY(asset = material, advanced)
u32 material{0};
ES_PROPERTY()
diff --git a/src/esengine/ecs/components/TilemapLayer.hpp b/src/esengine/ecs/components/TilemapLayer.hpp
index edb98fd28..0eac1f8a7 100644
--- a/src/esengine/ecs/components/TilemapLayer.hpp
+++ b/src/esengine/ecs/components/TilemapLayer.hpp
@@ -29,19 +29,19 @@ struct TilemapLayer {
ES_PROPERTY(asset = texture)
resource::TextureHandle tileset;
- ES_PROPERTY()
+ ES_PROPERTY(min=1, step=1)
i32 tilesetColumns{1};
- ES_PROPERTY()
+ ES_PROPERTY(min=1, step=1)
i32 tilesetRows{1};
- ES_PROPERTY()
+ ES_PROPERTY(step=1, enum_source=sortingLayers)
i32 renderLayer{0};
ES_PROPERTY(animatable)
glm::vec4 tintColor{1.0f, 1.0f, 1.0f, 1.0f};
- ES_PROPERTY(animatable)
+ ES_PROPERTY(animatable, min=0, max=1, slider, tooltip="Layer transparency (0 = invisible, 1 = opaque).")
f32 opacity{1.0f};
ES_PROPERTY()
diff --git a/src/esengine/ecs/components/Transform.hpp b/src/esengine/ecs/components/Transform.hpp
index 89e0995b5..22a00a3a1 100644
--- a/src/esengine/ecs/components/Transform.hpp
+++ b/src/esengine/ecs/components/Transform.hpp
@@ -40,13 +40,13 @@ namespace esengine::ecs {
*/
ES_COMPONENT()
struct Transform {
- ES_PROPERTY(animatable, anim_override)
+ ES_PROPERTY(animatable, anim_override, tooltip="Local position in world units, relative to the parent.")
glm::vec3 position{0.0f, 0.0f, 0.0f};
- ES_PROPERTY(animatable, anim_override)
+ ES_PROPERTY(animatable, anim_override, tooltip="Rotation about the Z axis, in degrees.")
glm::quat rotation{1.0f, 0.0f, 0.0f, 0.0f};
- ES_PROPERTY(animatable, anim_override)
+ ES_PROPERTY(animatable, anim_override, tooltip="Local scale per axis (1 = original size; negative flips).")
glm::vec3 scale{1.0f, 1.0f, 1.0f};
ES_PROPERTY(readonly)
diff --git a/tools/eht/__main__.py b/tools/eht/__main__.py
index 7797983cb..fc4bb9f24 100644
--- a/tools/eht/__main__.py
+++ b/tools/eht/__main__.py
@@ -35,6 +35,13 @@ def main() -> int:
if cpp_parser.warnings:
cpp_parser.print_warnings()
+ # Abort before codegen on malformed metadata — emitting bindings from a bad
+ # annotation would bake the mistake into committed *.generated.* files.
+ if cpp_parser.errors:
+ cpp_parser.print_errors()
+ print(f"[FAIL] {len(cpp_parser.errors)} annotation error(s); aborting before codegen.")
+ return 1
+
# Emit components/enums in a stable alphabetical order so the generated files
# are byte-reproducible across machines — Path.rglob order is filesystem-
# dependent, which otherwise churns every committed *.generated.* file when a
diff --git a/tools/eht/generators/metadata.py b/tools/eht/generators/metadata.py
index 1840d0abf..8c441d1f7 100644
--- a/tools/eht/generators/metadata.py
+++ b/tools/eht/generators/metadata.py
@@ -1,10 +1,11 @@
"""Component metadata generator (component.generated.ts)."""
-from typing import Dict, List, Optional
+import json
+from typing import Dict, List, Optional, Tuple
from ..data import Component, Enum, Property
from ..type_system import TypeSystem
from ..field_utils import (
- is_color_field, build_enum_value_map, convert_default_ts,
+ is_color_field, build_enum_value_map, convert_default_ts, format_number,
)
@@ -45,6 +46,43 @@ class MetadataGenerator:
def _get_color_fields(self, comp: Component) -> List[str]:
return [p.name for p in comp.properties if is_color_field(p, self.types)]
+ def _get_field_meta(self, comp: Component) -> List[Tuple[str, List[Tuple[str, str]]]]:
+ """Build per-field editor-presentation metadata (the FieldMeta shape) from
+ ES_PROPERTY annotations. `enum`/`flags`/`gradient`/`curve` are intentionally
+ absent — they carry runtime TS constants (e.g. enumOptions(...)) and stay as
+ TS-side defineBuiltin overrides; everything expressible as a static annotation
+ is authored at the C++ site. Returns [(field, [(metaKey, jsLiteral), ...])].
+ """
+ out: List[Tuple[str, List[Tuple[str, str]]]] = []
+ for prop in comp.properties:
+ a = prop.annotations
+ entries: List[Tuple[str, str]] = []
+ if 'min' in a:
+ entries.append(('min', format_number(a['min'])))
+ if 'max' in a:
+ entries.append(('max', format_number(a['max'])))
+ if 'step' in a:
+ entries.append(('step', format_number(a['step'])))
+ if 'slider' in a:
+ entries.append(('slider', 'true'))
+ if 'unit' in a:
+ entries.append(('unit', json.dumps(a['unit'], ensure_ascii=False)))
+ if 'label' in a:
+ entries.append(('label', json.dumps(a['label'], ensure_ascii=False)))
+ if 'tooltip' in a:
+ entries.append(('tooltip', json.dumps(a['tooltip'], ensure_ascii=False)))
+ if 'category' in a:
+ entries.append(('category', json.dumps(a['category'], ensure_ascii=False)))
+ if 'advanced' in a:
+ entries.append(('advanced', 'true'))
+ if 'enum_source' in a:
+ entries.append(('enumSource', json.dumps(a['enum_source'], ensure_ascii=False)))
+ if 'bitmask_source' in a:
+ entries.append(('bitmask', '{ source: ' + json.dumps(a['bitmask_source'], ensure_ascii=False) + ' }'))
+ if entries:
+ out.append((prop.name, entries))
+ return out
+
def _get_animatable_fields(self, comp: Component) -> List[str]:
fields = []
for prop in comp.properties:
@@ -75,6 +113,7 @@ class MetadataGenerator:
' */',
'',
"import type { AssetFieldType } from './scene';",
+ "import type { FieldMeta } from './component';",
'',
'/**',
' * Single-source-of-truth hash of the C++/TS boundary ABI (component',
@@ -101,6 +140,7 @@ class MetadataGenerator:
' entityFields: string[];',
' colorFields: string[];',
' animatableFields: string[];',
+ ' fields?: Record<string, FieldMeta>;',
'}',
'',
'export const COMPONENT_META: Record<string, ComponentMetaEntry> = {',
@@ -158,6 +198,14 @@ class MetadataGenerator:
else:
lines.append(' animatableFields: [],')
+ field_meta = self._get_field_meta(comp)
+ if field_meta:
+ lines.append(' fields: {')
+ for fname, entries in field_meta:
+ parts = ', '.join(f'{k}: {v}' for k, v in entries)
+ lines.append(f' {fname}: {{ {parts} }},')
+ lines.append(' },')
+
lines.append(' },')
lines.append('};')
diff --git a/tools/eht/parser.py b/tools/eht/parser.py
index d315460ac..3baa481ae 100644
--- a/tools/eht/parser.py
+++ b/tools/eht/parser.py
@@ -7,23 +7,54 @@ from typing import Dict, List
from .data import Component, Enum, Property
+def _is_number(s: str) -> bool:
+ try:
+ float(s)
+ return True
+ except (TypeError, ValueError):
+ return False
+
+
class CppParser:
"""Parses C++ headers and extracts component/enum definitions."""
RE_NAMESPACE = re.compile(r'namespace\s+([\w:]+)\s*\{')
RE_COMPONENT = re.compile(r'ES_COMPONENT\s*\(\s*\)\s*struct\s+(\w+)')
RE_ENUM = re.compile(r'ES_ENUM\s*\(\s*\)\s*enum\s+class\s+(\w+)(?:\s*:\s*(\w+))?')
+ # The annotation group `(?:[^)"]|"[^"]*")*?` accepts runs of non-paren chars
+ # OR whole quoted strings, so a `)` or `,` *inside quotes* (e.g. a tooltip) does
+ # not terminate the argument list. Non-greedy stops at the first UNquoted `)`.
RE_PROPERTY = re.compile(
- r'ES_PROPERTY\s*\(\s*([^)]*)\s*\)\s*'
+ r'ES_PROPERTY\s*\(\s*((?:[^)"]|"[^"]*")*?)\s*\)\s*'
r'([^;]+?)\s+(\w+)\s*'
r'(?:\{([^}]*)\}|=\s*([^;]+))?;'
)
RE_ENUM_VALUE = re.compile(r'(\w+)\s*(?:=\s*\d+)?\s*,?')
+ # ES_PROPERTY annotation vocabulary (RC9-1: ES_PROPERTY is the single authoring
+ # site for editor/serialization metadata). FLAG annotations take no value; KV
+ # annotations require `key=value`. A key outside both sets is an unknown
+ # annotation (warning, for forward-compat); malformed *known* metadata is a hard
+ # error (see _validate_annotations) — silently dropping it is the exact failure
+ # RC9-1 kills.
+ FLAG_ANNOTATIONS = frozenset({
+ 'animatable', 'anim_override', 'entity_ref', 'readonly',
+ 'slider', 'advanced', 'skip_serialize', 'replicated',
+ })
+ KV_ANNOTATIONS = frozenset({
+ 'asset', 'anim_flag', 'min', 'max', 'step', 'unit', 'label',
+ 'tooltip', 'category', 'enum_source', 'bitmask_source', 'invalidates',
+ })
+ NUMERIC_ANNOTATIONS = frozenset({'min', 'max', 'step'})
+ VALID_ASSET_TYPES = frozenset({
+ 'texture', 'material', 'font', 'audio', 'spine_skeleton', 'spine_atlas',
+ })
+
def __init__(self):
self.components: List[Component] = []
self.enums: List[Enum] = []
self.warnings: List[str] = []
+ self.errors: List[str] = []
def parse_file(self, filepath: Path) -> None:
content = filepath.read_text(encoding='utf-8')
@@ -81,7 +112,7 @@ class CppParser:
default = prop_match.group(4) or prop_match.group(5)
# Validate annotations
- self._validate_annotations(comp_name, prop_name, cpp_type, annotations, filepath)
+ self._validate_annotations(comp_name, prop_name, annotations, filepath)
component.properties.append(Property(
name=prop_name, cpp_type=cpp_type,
@@ -94,43 +125,88 @@ class CppParser:
f"{filepath}:{comp_name}: ES_COMPONENT with no ES_PROPERTY fields"
)
+ self._validate_component_refs(component, filepath)
self.components.append(component)
- def _validate_annotations(self, comp_name: str, prop_name: str, cpp_type: str,
+ def _validate_annotations(self, comp_name: str, prop_name: str,
annotations: Dict[str, str], filepath: Path) -> None:
- """Validate annotation usage and emit warnings for likely mistakes."""
- known_annotations = {'animatable', 'anim_override', 'asset', 'entity_ref', 'readonly'}
-
- for key in annotations:
- if key not in known_annotations and '=' not in key:
- self.warnings.append(
- f"{filepath}:{comp_name}.{prop_name}: "
- f"unknown annotation '{key}' (known: {', '.join(sorted(known_annotations))})"
- )
-
- if 'asset' in annotations:
- valid_asset_types = {'texture', 'material', 'font', 'audio', 'spine_skeleton', 'spine_atlas'}
- asset_type = annotations['asset']
- if asset_type not in valid_asset_types:
- self.warnings.append(
- f"{filepath}:{comp_name}.{prop_name}: "
- f"unknown asset type '{asset_type}' (known: {', '.join(sorted(valid_asset_types))})"
+ """Validate per-property annotation syntax.
+
+ Malformed *known* metadata is a hard error: a numeric annotation that isn't
+ a number, or `slider` without a range, would be silently dropped by the
+ generators — the exact failure mode RC9-1 exists to kill. Unknown keys stay
+ warnings (forward-compat). Flags are presence-based; their value is ignored.
+ """
+ loc = f"{filepath}:{comp_name}.{prop_name}"
+
+ for key, value in annotations.items():
+ if key not in self.FLAG_ANNOTATIONS and key not in self.KV_ANNOTATIONS:
+ known = ', '.join(sorted(self.FLAG_ANNOTATIONS | self.KV_ANNOTATIONS))
+ self.warnings.append(f"{loc}: unknown annotation '{key}' (known: {known})")
+ continue
+ if key in self.NUMERIC_ANNOTATIONS and not _is_number(value):
+ self.errors.append(f"{loc}: annotation {key}='{value}' must be numeric")
+
+ if 'slider' in annotations and not ('min' in annotations and 'max' in annotations):
+ self.errors.append(f"{loc}: slider requires both min= and max= on the same field")
+
+ asset_type = annotations.get('asset')
+ if asset_type is not None and asset_type not in self.VALID_ASSET_TYPES:
+ known = ', '.join(sorted(self.VALID_ASSET_TYPES))
+ self.warnings.append(f"{loc}: unknown asset type '{asset_type}' (known: {known})")
+
+ def _validate_component_refs(self, component: Component, filepath: Path) -> None:
+ """Component-level checks that need the full field set — currently
+ `invalidates=<field>` must name a sibling property (else the generated
+ setter side-effect would reference a non-existent member)."""
+ field_names = {p.name for p in component.properties}
+ for prop in component.properties:
+ target = prop.annotations.get('invalidates')
+ if target is not None and target not in field_names:
+ self.errors.append(
+ f"{filepath}:{component.name}.{prop.name}: "
+ f"invalidates='{target}' names no field on this component"
)
@staticmethod
def _parse_annotations(raw: str) -> Dict[str, str]:
result: Dict[str, str] = {}
- for token in raw.split(','):
+ for token in CppParser._split_top_level(raw):
token = token.strip()
if not token:
continue
if '=' in token:
key, value = token.split('=', 1)
- result[key.strip()] = value.strip()
+ result[key.strip()] = CppParser._unquote(value.strip())
else:
result[token] = 'true'
return result
+ @staticmethod
+ def _split_top_level(raw: str) -> List[str]:
+ """Split on commas that are not inside a double-quoted string, so a quoted
+ value (`tooltip="a, b"`) stays one token."""
+ parts: List[str] = []
+ buf: List[str] = []
+ in_str = False
+ for ch in raw:
+ if ch == '"':
+ in_str = not in_str
+ buf.append(ch)
+ elif ch == ',' and not in_str:
+ parts.append(''.join(buf))
+ buf = []
+ else:
+ buf.append(ch)
+ parts.append(''.join(buf))
+ return parts
+
+ @staticmethod
+ def _unquote(s: str) -> str:
+ if len(s) >= 2 and s[0] == '"' and s[-1] == '"':
+ return s[1:-1]
+ return s
+
def parse_directory(self, dirpath: Path) -> None:
for filepath in dirpath.rglob('*.hpp'):
try:
@@ -142,3 +218,8 @@ class CppParser:
"""Print all accumulated warnings to stderr."""
for w in self.warnings:
print(f" WARNING: {w}", file=sys.stderr)
+
+ def print_errors(self) -> None:
+ """Print all accumulated hard errors to stderr."""
+ for e in self.errors:
+ print(f" ERROR: {e}", file=sys.stderr)
diff --git a/tools/eht/test_validation.py b/tools/eht/test_validation.py
new file mode 100644
index 000000000..7e19da1bb
--- /dev/null
+++ b/tools/eht/test_validation.py
@@ -0,0 +1,118 @@
+"""Plain-python tests for ES_PROPERTY annotation validation (RC9-1 P0).
+
+No pytest dependency — run: python3 tools/eht/test_validation.py
+Exits non-zero on the first failing case.
+"""
+
+import sys
+import tempfile
+from pathlib import Path
+
+sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) # put tools/ on path
+from eht.parser import CppParser # noqa: E402
+
+HEADER = """
+namespace esengine::ecs {{
+ES_COMPONENT()
+struct C {{
+{body}
+}};
+}}
+"""
+
+_failures = 0
+
+
+def _parse(body: str) -> CppParser:
+ p = CppParser()
+ with tempfile.TemporaryDirectory() as d:
+ f = Path(d) / 'C.hpp'
+ f.write_text(HEADER.format(body=body), encoding='utf-8')
+ p.parse_file(f)
+ return p
+
+
+def expect(name: str, body: str, *, errors: int, warnings_at_least: int = 0) -> None:
+ global _failures
+ p = _parse(body)
+ problems = []
+ if len(p.errors) != errors:
+ problems.append(f"errors: got {len(p.errors)} want {errors} -> {p.errors}")
+ if len(p.warnings) < warnings_at_least:
+ problems.append(f"warnings: got {len(p.warnings)} want >= {warnings_at_least} -> {p.warnings}")
+ if problems:
+ _failures += 1
+ print(f"FAIL {name}")
+ for pr in problems:
+ print(f" {pr}")
+ else:
+ print(f"ok {name}")
+
+
+# ── Positives: well-formed metadata produces no errors ──
+expect('full presentation metadata',
+ 'ES_PROPERTY(min=0, max=10, slider, unit="x", tooltip="hi", category="Grp", advanced)\n float x = 0.0f;',
+ errors=0)
+expect('anim_flag is a known kv annotation',
+ 'ES_PROPERTY(animatable, anim_flag=ANIM_POS_X)\n float y = 0.0f;',
+ errors=0)
+expect('invalidates names a sibling (order-independent)',
+ 'ES_PROPERTY(invalidates=foo)\n std::string s{};\n ES_PROPERTY()\n bool foo = false;',
+ errors=0)
+expect('existing asset annotation still clean',
+ 'ES_PROPERTY(asset=texture)\n u32 tex = 0;',
+ errors=0)
+expect('skip_serialize / replicated flags accepted',
+ 'ES_PROPERTY(skip_serialize, replicated)\n float z = 0.0f;',
+ errors=0)
+
+# ── Negatives: malformed known metadata is a hard error ──
+expect('non-numeric min is an error',
+ 'ES_PROPERTY(min=abc)\n float x = 0.0f;',
+ errors=1)
+expect('slider without a range is an error',
+ 'ES_PROPERTY(slider)\n float x = 0.0f;',
+ errors=1)
+expect('slider with only min is an error',
+ 'ES_PROPERTY(slider, min=0)\n float x = 0.0f;',
+ errors=1)
+expect('invalidates naming no field is an error',
+ 'ES_PROPERTY(invalidates=nope)\n std::string s{};',
+ errors=1)
+
+# ── Quoted values carry commas and parens (tooltips) without breaking tokenizing ──
+def quoted_ok(name: str, body: str, field: str, key: str, expected: str) -> None:
+ global _failures
+ p = _parse(body)
+ got = None
+ for c in p.components:
+ for pr in c.properties:
+ if pr.name == field:
+ got = pr.annotations.get(key)
+ if len(p.errors) != 0 or got != expected:
+ _failures += 1
+ print(f"FAIL {name}")
+ print(f" errors={p.errors} annotations.{key}={got!r} want {expected!r}")
+ else:
+ print(f"ok {name}")
+
+
+quoted_ok('tooltip with commas + parens stays one token',
+ 'ES_PROPERTY(min=0, tooltip="Falloff reach (Point / Spot), in units.")\n float radius = 0.0f;',
+ 'radius', 'tooltip', 'Falloff reach (Point / Spot), in units.')
+quoted_ok('quotes are stripped from the value',
+ 'ES_PROPERTY(unit="deg")\n float a = 0.0f;',
+ 'a', 'unit', 'deg')
+
+# ── Unknown keys stay warnings, not errors (forward-compat) ──
+expect('unknown annotation is a warning, not an error',
+ 'ES_PROPERTY(bogus)\n float x = 0.0f;',
+ errors=0, warnings_at_least=1)
+expect('unknown asset type is a warning, not an error',
+ 'ES_PROPERTY(asset=widget)\n u32 a = 0;',
+ errors=0, warnings_at_least=1)
+
+if _failures:
+ print(f"\n{_failures} case(s) failed")
+ raise SystemExit(1)
+print("\nall cases passed")