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(eht): editor_default annotation — creation defaults single-sourced from C++

yhh07c91f2b3a2b
diff --git a/sdk/src/component.generated.ts b/sdk/src/component.generated.ts
index 2ffa3e1f8..cd46b8493 100644
--- a/sdk/src/component.generated.ts
+++ b/sdk/src/component.generated.ts
@@ -29,6 +29,13 @@ export interface SpineFieldMeta {
export interface ComponentMetaEntry {
defaults: Record<string, unknown>;
+ /**
+ * Creation-time overrides authored at the C++ ES_PROPERTY site via
+ * `editor_default=` — where the authoring default deliberately differs
+ * from the C++ ctor value in `defaults`. Component registration merges
+ * these over `defaults`; `defaults` alone is the runtime ctor truth.
+ */
+ editorDefaults?: Record<string, unknown>;
assetFields: AssetFieldMeta[];
spine?: SpineFieldMeta;
entityFields: string[];
@@ -90,6 +97,12 @@ export const COMPONENT_META: Record<string, ComponentMetaEntry> = {
clearFlags: 3,
pixelPerfect: false,
},
+ editorDefaults: {
+ projectionType: 1,
+ orthoSize: 540,
+ aspectRatio: 1.77,
+ isActive: true,
+ },
assetFields: [],
entityFields: [],
colorFields: [],
@@ -442,6 +455,9 @@ export const COMPONENT_META: Record<string, ComponentMetaEntry> = {
material: 0,
enabled: true,
},
+ editorDefaults: {
+ size: { x: 100, y: 100 },
+ },
assetFields: [{ field: 'texture', type: 'texture' as AssetFieldType }, { field: 'material', type: 'material' as AssetFieldType }],
entityFields: [],
colorFields: ['color'],
diff --git a/sdk/src/component.ts b/sdk/src/component.ts
index 6d45c56b6..2a0ebc808 100644
--- a/sdk/src/component.ts
+++ b/sdk/src/component.ts
@@ -6,7 +6,6 @@
*/
import { Entity, Vec2, Vec3, Color, Quat } from './types';
-import { DEFAULT_SPRITE_SIZE } from './defaults';
import { COMPONENT_META, type AssetFieldMeta, type SpineFieldMeta } from './component.generated';
// C++-backed component data shapes, generated from the ES_COMPONENT structs (single
// source — a TS field can no longer drift from C++). Re-exported below so the public
@@ -525,7 +524,7 @@ export function defineBuiltin<T>(name: string, defaults: T, metadata?: Component
export function ensureBuiltinComponentsRegistered(): void {
for (const name of Object.keys(COMPONENT_META)) {
if (!builtinRegistry.has(name)) {
- defineBuiltin(name, COMPONENT_META[name].defaults as Record<string, unknown>);
+ defineBuiltin(name, metaDefaults<Record<string, unknown>>(name));
}
}
}
@@ -590,9 +589,17 @@ export interface SceneOwnerData {
// Builtin Component Instances
// =============================================================================
+// Creation defaults = C++ ctor values ⊕ `editor_default=` annotation overrides
+// (both EHT-generated) ⊕ TS-only-field overrides from the call site. This is the
+// single place authoring defaults are assembled — a builtin's _default carries
+// the merged result.
function metaDefaults<T>(name: string, overrides?: Partial<T>): T {
- const base = COMPONENT_META[name]?.defaults ?? {};
- return (overrides ? { ...base, ...overrides } : { ...base }) as T;
+ const meta = COMPONENT_META[name];
+ return {
+ ...meta?.defaults,
+ ...meta?.editorDefaults,
+ ...overrides,
+ } as T;
}
// Field presentation metadata (min/max/tooltip/category/…) is authored at the C++
@@ -606,10 +613,10 @@ export const Transform = defineBuiltin<TransformData>('Transform',
export const LocalTransform = Transform;
export const WorldTransform = Transform;
+// size's authoring default (100×100 vs the {1,1} ctor value) is authored at the
+// C++ ES_PROPERTY site (editor_default=) and merged in by metaDefaults.
export const Sprite = defineBuiltin<SpriteData>('Sprite',
- metaDefaults<SpriteData>('Sprite', {
- size: { x: DEFAULT_SPRITE_SIZE.x, y: DEFAULT_SPRITE_SIZE.y },
- })
+ metaDefaults<SpriteData>('Sprite')
);
// shapeType's dropdown is generated from the C++ ShapeType enum (ES_PROPERTY enum=).
@@ -626,12 +633,12 @@ export const ShadowCaster2D = defineBuiltin<ShadowCaster2DData>('ShadowCaster2D'
metaDefaults<ShadowCaster2DData>('ShadowCaster2D')
);
+// The authoring defaults that differ from the C++ ctor (an active Orthographic
+// at orthoSize 540 vs a Perspective/inactive runtime default) are authored at
+// the C++ ES_PROPERTY sites (editor_default=) and merged in by metaDefaults.
+// Only the TS-only field's default stays here.
export const Camera = defineBuiltin<CameraData>('Camera',
metaDefaults<CameraData>('Camera', {
- projectionType: ProjectionType.Orthographic,
- orthoSize: 540,
- aspectRatio: 1.77,
- isActive: true,
showFrustum: false,
}),
{
diff --git a/sdk/src/defaults.ts b/sdk/src/defaults.ts
index 3bb438f96..12eb44c77 100644
--- a/sdk/src/defaults.ts
+++ b/sdk/src/defaults.ts
@@ -1,13 +1,23 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
import { CanvasScaleMode } from './wasm.generated';
+import { COMPONENT_META } from './component.generated';
import { getResourceManager, setTextureBudget } from './resourceManager';
-export const DEFAULT_DESIGN_WIDTH = 1920;
-export const DEFAULT_DESIGN_HEIGHT = 1080;
-export const DEFAULT_PIXELS_PER_UNIT = 100;
+// Values with a C++ backing read the generated metadata (Canvas ctor defaults,
+// Sprite's editor_default annotation) so these constants cannot drift from the
+// ES_PROPERTY sites they restate.
+const canvasDefaults = COMPONENT_META.Canvas.defaults as {
+ designResolution: { x: number; y: number };
+ pixelsPerUnit: number;
+};
+export const DEFAULT_DESIGN_WIDTH = canvasDefaults.designResolution.x;
+export const DEFAULT_DESIGN_HEIGHT = canvasDefaults.designResolution.y;
+export const DEFAULT_PIXELS_PER_UNIT = canvasDefaults.pixelsPerUnit;
export const DEFAULT_TEXT_CANVAS_SIZE = 512;
-export const DEFAULT_SPRITE_SIZE = { x: 100, y: 100 };
+export const DEFAULT_SPRITE_SIZE = {
+ ...(COMPONENT_META.Sprite.editorDefaults as { size: { x: number; y: number } }).size,
+};
export const DEFAULT_FONT_FAMILY = 'Arial';
export const DEFAULT_FONT_SIZE = 24;
export const DEFAULT_LINE_HEIGHT = 1.2;
diff --git a/sdk/tests/editor-defaults.test.ts b/sdk/tests/editor-defaults.test.ts
new file mode 100644
index 000000000..87de34e86
--- /dev/null
+++ b/sdk/tests/editor-defaults.test.ts
@@ -0,0 +1,43 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file Creation-default single-sourcing: authoring defaults that differ from
+ * the C++ ctor are authored at the ES_PROPERTY site (editor_default=),
+ * flow through COMPONENT_META.editorDefaults, and are merged into the
+ * registered builtin's _default. Both layers stay observable — defaults
+ * is the runtime ctor truth, _default the authoring truth.
+ */
+import { describe, it, expect } from 'vitest';
+import { Camera, Sprite, ProjectionType } from '../src/component';
+import { COMPONENT_META } from '../src/component.generated';
+import { DEFAULT_SPRITE_SIZE } from '../src/defaults';
+
+describe('editor_default single-source', () => {
+ it('Camera authors as an active Orthographic while the ctor stays Perspective/inactive', () => {
+ const ctor = COMPONENT_META.Camera.defaults as Record<string, unknown>;
+ expect(ctor.projectionType).toBe(ProjectionType.Perspective);
+ expect(ctor.orthoSize).toBe(5);
+ expect(ctor.isActive).toBe(false);
+
+ const authored = Camera._default;
+ expect(authored.projectionType).toBe(ProjectionType.Orthographic);
+ expect(authored.orthoSize).toBe(540);
+ expect(authored.aspectRatio).toBeCloseTo(1.77);
+ expect(authored.isActive).toBe(true);
+ expect(authored.showFrustum).toBe(false);
+ });
+
+ it('Sprite authors at 100px while the ctor stays {1,1} world units', () => {
+ const ctor = COMPONENT_META.Sprite.defaults as { size: { x: number; y: number } };
+ expect(ctor.size).toEqual({ x: 1, y: 1 });
+
+ expect(Sprite._default.size).toEqual({ x: 100, y: 100 });
+ });
+
+ it('DEFAULT_SPRITE_SIZE derives from the annotation, not a hand copy', () => {
+ expect(DEFAULT_SPRITE_SIZE).toEqual({ x: 100, y: 100 });
+ const generated = (COMPONENT_META.Sprite.editorDefaults as { size: object }).size;
+ expect(DEFAULT_SPRITE_SIZE).toEqual(generated);
+ expect(DEFAULT_SPRITE_SIZE).not.toBe(generated);
+ });
+});
diff --git a/src/esengine/bindings/EditorAPI.generated.cpp b/src/esengine/bindings/EditorAPI.generated.cpp
index 6c9990061..f093c80b4 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 3e406753fbcb117c
+ * @schema_hash 9a8aa5c2786aab04
*/
-#define ES_EDITOR_API_SCHEMA_HASH "3e406753fbcb117c"
+#define ES_EDITOR_API_SCHEMA_HASH "9a8aa5c2786aab04"
#include <emscripten/bind.h>
#include <string>
diff --git a/src/esengine/ecs/components/Camera.hpp b/src/esengine/ecs/components/Camera.hpp
index 2f28f5ec0..b083dfe65 100644
--- a/src/esengine/ecs/components/Camera.hpp
+++ b/src/esengine/ecs/components/Camera.hpp
@@ -69,7 +69,7 @@ enum class ClearFlags : u8 {
ES_COMPONENT()
struct Camera {
/** @brief Projection type */
- ES_PROPERTY(tooltip="Orthographic (2D) or Perspective projection.")
+ ES_PROPERTY(tooltip="Orthographic (2D) or Perspective projection.", editor_default=ProjectionType::Orthographic)
ProjectionType projectionType{ProjectionType::Perspective};
/** @brief Field of view in degrees (perspective only) */
@@ -77,7 +77,7 @@ struct Camera {
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).")
+ ES_PROPERTY(animatable, min=0, tooltip="Half the visible height in world units (Orthographic).", editor_default=540)
f32 orthoSize{5.0f};
/** @brief Near clipping plane distance */
@@ -89,11 +89,11 @@ struct Camera {
f32 farPlane{1000.0f};
/** @brief Aspect ratio (width / height), 0 = auto from viewport */
- ES_PROPERTY(advanced)
+ ES_PROPERTY(advanced, editor_default=1.77)
f32 aspectRatio{0.0f};
/** @brief Whether this is the active camera */
- ES_PROPERTY()
+ ES_PROPERTY(editor_default=true)
bool isActive{false};
/** @brief Priority for determining active camera (higher = preferred) */
diff --git a/src/esengine/ecs/components/Sprite.hpp b/src/esengine/ecs/components/Sprite.hpp
index 7b144e051..ffeda575a 100644
--- a/src/esengine/ecs/components/Sprite.hpp
+++ b/src/esengine/ecs/components/Sprite.hpp
@@ -53,8 +53,8 @@ struct Sprite {
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 */
- ES_PROPERTY(animatable)
+ /** @brief Sprite size in world units ({1,1} at runtime; authored at 100px) */
+ ES_PROPERTY(animatable, editor_default={100, 100})
glm::vec2 size{1.0f, 1.0f};
/** @brief Pivot point (0,0 = bottom-left, 0.5,0.5 = center, 1,1 = top-right) */
diff --git a/tools/eht/generators/metadata.py b/tools/eht/generators/metadata.py
index e1d3987f6..087c7a9f6 100644
--- a/tools/eht/generators/metadata.py
+++ b/tools/eht/generators/metadata.py
@@ -9,6 +9,14 @@ from ..field_utils import (
)
+def _is_number(s: str) -> bool:
+ try:
+ float(s.rstrip('fF'))
+ return True
+ except (TypeError, ValueError):
+ return False
+
+
class MetadataGenerator:
"""Generates component.generated.ts with defaults and metadata."""
@@ -96,6 +104,51 @@ class MetadataGenerator:
out.append((prop.name, entries))
return out
+ def _get_editor_defaults(self, comp: Component) -> List[Tuple[str, str]]:
+ """Collect `editor_default=` creation overrides as [(field, tsLiteral)].
+
+ The value goes through the SAME converter as the C++ ctor default, so an
+ annotation supports exactly the member-initializer grammar (number, bool,
+ Enum::Member, braced vector). A value the converter would silently turn
+ into 0 is a hard error — a wrong creation default baked into the generated
+ file is the drift this annotation exists to kill.
+ """
+ out: List[Tuple[str, str]] = []
+ for prop in comp.properties:
+ raw = prop.annotations.get('editor_default')
+ if raw is None:
+ continue
+ loc = f'{comp.name}.{prop.name}'
+ t = self.types.clean_type(prop.cpp_type)
+ if self.types.is_enum(t):
+ member = raw.split('::')[-1].strip()
+ enum_short = t.split('::')[-1]
+ vals = self.types.get_enum_values(t)
+ if member not in (vals or []):
+ raise ValueError(
+ f"{loc}: editor_default '{raw}' names no member of {enum_short}")
+ # convert_default_ts resolves enum members from a `X::Member`
+ # form; normalize so `editor_default=Orthographic` also works.
+ raw = f'{enum_short}::{member}'
+ elif t == 'bool':
+ if raw not in ('true', 'false'):
+ raise ValueError(f"{loc}: editor_default '{raw}' must be true or false")
+ elif t in TypeSystem.PRIMITIVE_TYPES:
+ if not _is_number(raw):
+ raise ValueError(f"{loc}: editor_default '{raw}' must be numeric")
+ elif t in TypeSystem.GLM_TYPES:
+ if not (raw.startswith('{') and raw.endswith('}')):
+ raise ValueError(
+ f"{loc}: editor_default '{raw}' must be a braced initializer for {t}")
+ else:
+ raise ValueError(
+ f"{loc}: editor_default is not supported for type '{prop.cpp_type}'")
+ shadow = Property(name=prop.name, cpp_type=prop.cpp_type,
+ default_value=raw.strip().strip('{}') if t in TypeSystem.GLM_TYPES else raw,
+ annotations=prop.annotations)
+ out.append((prop.name, convert_default_ts(shadow, self.types, self._enum_values)))
+ return out
+
def _get_animatable_fields(self, comp: Component) -> List[str]:
fields = []
for prop in comp.properties:
@@ -232,6 +285,13 @@ class MetadataGenerator:
'',
'export interface ComponentMetaEntry {',
' defaults: Record<string, unknown>;',
+ ' /**',
+ ' * Creation-time overrides authored at the C++ ES_PROPERTY site via',
+ ' * `editor_default=` — where the authoring default deliberately differs',
+ ' * from the C++ ctor value in `defaults`. Component registration merges',
+ ' * these over `defaults`; `defaults` alone is the runtime ctor truth.',
+ ' */',
+ ' editorDefaults?: Record<string, unknown>;',
' assetFields: AssetFieldMeta[];',
' spine?: SpineFieldMeta;',
' entityFields: string[];',
@@ -262,6 +322,13 @@ class MetadataGenerator:
lines.append(f' {prop.name}: {val},')
lines.append(' },')
+ editor_defaults = self._get_editor_defaults(comp)
+ if editor_defaults:
+ lines.append(' editorDefaults: {')
+ for fname, val in editor_defaults:
+ lines.append(f' {fname}: {val},')
+ lines.append(' },')
+
if asset_fields:
parts = ', '.join(
f"{{ field: '{f['field']}', type: '{f['type']}' as AssetFieldType }}"
diff --git a/tools/eht/parser.py b/tools/eht/parser.py
index e59b8e4e2..c77a76c73 100644
--- a/tools/eht/parser.py
+++ b/tools/eht/parser.py
@@ -52,6 +52,13 @@ class CppParser:
# editor dropdown from that enum's values — for fields kept as i32 (not the
# enum type) but still single-choice. Enum-TYPED fields need no annotation.
'enum',
+ # `editor_default=<value>` authors the CREATION default the editor uses when
+ # adding the component — where it deliberately differs from the C++ ctor
+ # value (e.g. Camera is Perspective/inactive at runtime but authored as an
+ # active Orthographic; Sprite.size is {1,1} world units but authored 100px).
+ # Same value grammar as a C++ member initializer: number, true/false,
+ # Enum::Member, or a braced vector `{100, 100}`.
+ 'editor_default',
})
NUMERIC_ANNOTATIONS = frozenset({'min', 'max', 'step'})
VALID_ASSET_TYPES = frozenset({
@@ -192,16 +199,24 @@ class CppParser:
@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."""
+ """Split on commas that are not inside a double-quoted string or a braced
+ initializer, so `tooltip="a, b"` and `editor_default={100, 100}` each stay
+ one token."""
parts: List[str] = []
buf: List[str] = []
in_str = False
+ brace_depth = 0
for ch in raw:
if ch == '"':
in_str = not in_str
buf.append(ch)
- elif ch == ',' and not in_str:
+ elif ch == '{' and not in_str:
+ brace_depth += 1
+ buf.append(ch)
+ elif ch == '}' and not in_str:
+ brace_depth -= 1
+ buf.append(ch)
+ elif ch == ',' and not in_str and brace_depth == 0:
parts.append(''.join(buf))
buf = []
else:
diff --git a/tools/eht/test_validation.py b/tools/eht/test_validation.py
index 7e19da1bb..6a3b083b8 100644
--- a/tools/eht/test_validation.py
+++ b/tools/eht/test_validation.py
@@ -104,6 +104,57 @@ quoted_ok('quotes are stripped from the value',
'ES_PROPERTY(unit="deg")\n float a = 0.0f;',
'a', 'unit', 'deg')
+# ── editor_default: a braced initializer's commas must not split the token ──
+quoted_ok('editor_default braced vector stays one token',
+ 'ES_PROPERTY(animatable, editor_default={100, 100})\n glm::vec2 size{1.0f, 1.0f};',
+ 'size', 'editor_default', '{100, 100}')
+quoted_ok('editor_default enum member',
+ 'ES_PROPERTY(tooltip="p", editor_default=ProjectionType::Orthographic)\n ProjectionType p{ProjectionType::Perspective};',
+ 'p', 'editor_default', 'ProjectionType::Orthographic')
+quoted_ok('annotation after a braced editor_default still parses',
+ 'ES_PROPERTY(editor_default={1, 2}, advanced)\n glm::vec2 v{0.0f, 0.0f};',
+ 'v', 'advanced', 'true')
+
+
+# ── editor_default value validation lives in MetadataGenerator (typed) ──
+def editor_default_generates(name: str, body: str, expect_snippet: str) -> None:
+ global _failures
+ p = _parse(body)
+ from eht.generators.metadata import MetadataGenerator
+ from eht.data import Enum
+ enums = [Enum(name='ProjectionType', namespace='esengine::ecs',
+ values=['Perspective', 'Orthographic'])]
+ try:
+ out = MetadataGenerator(p.components, enums).generate()
+ except ValueError as e:
+ out = f'VALUEERROR: {e}'
+ if expect_snippet not in out:
+ _failures += 1
+ print(f"FAIL {name}")
+ print(f" {expect_snippet!r} not found in output")
+ else:
+ print(f"ok {name}")
+
+
+editor_default_generates('editor_default vec2 emits merged literal',
+ 'ES_PROPERTY(editor_default={100, 100})\n glm::vec2 size{1.0f, 1.0f};',
+ 'editorDefaults: {\n size: { x: 100, y: 100 },')
+editor_default_generates('editor_default enum member resolves to its index',
+ 'ES_PROPERTY(editor_default=ProjectionType::Orthographic)\n ProjectionType p{ProjectionType::Perspective};',
+ 'editorDefaults: {\n p: 1,')
+editor_default_generates('editor_default bare enum member also resolves',
+ 'ES_PROPERTY(editor_default=Orthographic)\n ProjectionType p{ProjectionType::Perspective};',
+ 'editorDefaults: {\n p: 1,')
+editor_default_generates('editor_default unknown enum member is a hard error',
+ 'ES_PROPERTY(editor_default=ProjectionType::Sideways)\n ProjectionType p{ProjectionType::Perspective};',
+ 'VALUEERROR')
+editor_default_generates('editor_default non-numeric on a float is a hard error',
+ 'ES_PROPERTY(editor_default=fast)\n float s = 1.0f;',
+ 'VALUEERROR')
+editor_default_generates('editor_default bool accepts true',
+ 'ES_PROPERTY(editor_default=true)\n bool active{false};',
+ 'editorDefaults: {\n active: true,')
+
# ── 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;',