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(inspector): a pivot is a fraction, and now the editor knows what of

yhhe0deffd1017f
diff --git a/desktop/scripts/editor-checks/sprite-pivot-pixels.mjs b/desktop/scripts/editor-checks/sprite-pivot-pixels.mjs
new file mode 100644
index 000000000..da25e9fb3
--- /dev/null
+++ b/desktop/scripts/editor-checks/sprite-pivot-pixels.mjs
@@ -0,0 +1,165 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file sprite-pivot-pixels — a pivot is a fraction, and the editor knows what of.
+ *
+ * `Sprite.pivot` is stored 0..1 so it survives a resize, but nobody authors in
+ * fractions — they author "32 pixels in from the left". The bridge is the
+ * `normalized_of=size` declaration on the C++ property: it tells the inspector
+ * which sibling is the denominator, and the row multiplies through it to offer a
+ * pixel view. That chain runs C++ → EHT → the generated TS meta → the inspector
+ * field, and every link is a place it can go quietly missing — a pixel view over
+ * a stale or absent denominator would show plausible numbers that write the wrong
+ * fraction.
+ *
+ * So: require the denominator to be reported, to TRACK the size rather than be
+ * baked once, and to stand down when it would divide by zero. Then check the
+ * geometry the preset grid encodes — which way a pivot actually moves a sprite —
+ * because a picker that writes a correct-looking number to the wrong axis is the
+ * failure no amount of metadata plumbing catches.
+ */
+import { makeProject, checker } from '../lib/editorDriver.mjs';
+
+const GREEN = [0, 255, 0];
+
+const SCENE = JSON.stringify({
+ version: '1.0', name: 'Main',
+ entities: [
+ {
+ id: 0, name: 'Camera', parent: null, children: [], visible: true,
+ components: [
+ { type: 'Transform', data: { position: { x: 0, y: 0, z: 10 } } },
+ { type: 'Camera', data: { projectionType: 1, orthoSize: 540, isActive: true, priority: 0 } },
+ ],
+ },
+ {
+ // Deliberately non-square: an axis swapped anywhere in the chain shows up as
+ // a denominator of 100 where 200 belongs, instead of hiding behind symmetry.
+ id: 1, name: 'Box', parent: null, children: [], visible: true,
+ components: [
+ { type: 'Transform', data: { position: { x: 0, y: 0, z: 0 } } },
+ { type: 'Sprite', data: { size: { x: 200, y: 100 }, color: { r: 0, g: 1, b: 0, a: 1 }, pivot: { x: 0.5, y: 0.5 } } },
+ ],
+ },
+ ],
+}, null, 1);
+
+const PROJECT = JSON.stringify({
+ formatVersion: '1', name: 'Sprite Pivot Check', version: '0.1.0',
+ defaultScene: 'assets/scenes/main.esscene',
+ designResolution: { width: 800, height: 600 },
+}, null, 2);
+
+export const name = 'sprite-pivot-pixels';
+export const describes = 'Sprite.pivot reports the size as its pixel denominator, and its presets move the sprite the way they read';
+
+/** Centroid of the pixels matching `want`, in PNG coordinates, or null if none do. */
+function centroid(png, want, tol = 60) {
+ let n = 0; let sx = 0; let sy = 0;
+ for (let y = 0; y < png.h; y++) {
+ for (let x = 0; x < png.w; x++) {
+ const p = png.px(x, y);
+ if (Math.abs(p[0] - want[0]) <= tol && Math.abs(p[1] - want[1]) <= tol && Math.abs(p[2] - want[2]) <= tol) {
+ n++; sx += x; sy += y;
+ }
+ }
+ }
+ return n > 0 ? { x: sx / n, y: sy / n, n } : null;
+}
+
+/** The Sprite's pivot field as the Details panel builds it. */
+async function pivotField(ed, entity) {
+ const comps = await ed.json('get_inspector', { entity }, 30000);
+ return comps.find((c) => c.name === 'Sprite')?.fields?.find((f) => f.key === 'pivot') ?? null;
+}
+
+const setSize = (ed, id, x, y) =>
+ ed.call('set_field', { entity: id, component: 'Sprite', key: 'size', type: 'vec2', value: [x, y] }, 30000);
+const setPivot = (ed, id, x, y) =>
+ ed.call('set_field', { entity: id, component: 'Sprite', key: 'pivot', type: 'vec2', value: [x, y] }, 30000);
+
+export async function run(ed) {
+ const root = await makeProject({ 'project.esproject': PROJECT, 'assets/scenes/main.esscene': SCENE });
+ const check = checker();
+
+ await ed.open(root, 'assets/scenes/main.esscene');
+ await ed.sleep(800);
+
+ const tree = await ed.json('get_scene_tree', {}, 30000);
+ const box = tree.find((e) => e.name === 'Box')?.id;
+ if (!check(box != null, 'the scene tree does not report the Box sprite')) return check.failures;
+
+ // — The declaration reaches the field —
+ const field = await pivotField(ed, box);
+ if (!check(field != null, 'the Sprite inspector has no pivot field at all')) return check.failures;
+ check(
+ field.advanced !== true,
+ 'pivot is still behind the Advanced fold — changing where a sprite turns is everyday authoring, '
+ + 'and a preset picker nobody can find is no picker',
+ );
+ check(
+ field.normalizedOf?.key === 'size',
+ `pivot reports no size denominator (${JSON.stringify(field.normalizedOf)}) — the normalized_of=size `
+ + 'declaration is not reaching the inspector, so the row can only offer raw fractions',
+ );
+ check(
+ JSON.stringify(field.normalizedOf?.denom) === JSON.stringify([200, 100]),
+ `pivot's denominator is ${JSON.stringify(field.normalizedOf?.denom)}, not the sprite's [200, 100] size`,
+ );
+
+ // — It tracks the sibling rather than being baked at build time —
+ await setSize(ed, box, 64, 32);
+ const resized = await pivotField(ed, box);
+ check(
+ JSON.stringify(resized?.normalizedOf?.denom) === JSON.stringify([64, 32]),
+ `after resizing to 64×32 the pivot denominator is still ${JSON.stringify(resized?.normalizedOf?.denom)} — `
+ + 'the pixel view is reading a stale size, so every pixel it shows is a lie',
+ );
+
+ // — And stands down where the arithmetic has no answer —
+ await setSize(ed, box, 0, 32);
+ const zeroed = await pivotField(ed, box);
+ check(
+ zeroed?.normalizedOf == null,
+ 'a zero-width sprite still offers a pixel view — every pixel entered would divide by zero',
+ );
+
+ // The renderer draws at `position - size * pivot`, so pivot (0,0) is the sprite's
+ // bottom-left corner and puts its body up and right of the origin — a SMALLER png y,
+ // world +Y being up. Backwards here and the grid's Top row moves a sprite down.
+ await setSize(ed, box, 200, 100);
+ await setPivot(ed, box, 0, 0);
+ const bottomLeft = centroid(await ed.capture('sprite-pivot-bottom-left'), GREEN);
+ await setPivot(ed, box, 1, 1);
+ const topRight = centroid(await ed.capture('sprite-pivot-top-right'), GREEN);
+ if (!check(bottomLeft && topRight, 'the sprite is not on screen in one of the two pivot states')) {
+ return check.failures;
+ }
+
+ const shiftX = bottomLeft.x - topRight.x;
+ const shiftY = topRight.y - bottomLeft.y;
+ check(
+ shiftX > 20,
+ `a bottom-left pivot puts the sprite at x=${bottomLeft.x.toFixed(0)} and a top-right one at `
+ + `x=${topRight.x.toFixed(0)} — moving it right by a full width is what pivot.x means, so the `
+ + 'X axis is inverted or ignored',
+ );
+ check(
+ shiftY > 10,
+ `a bottom-left pivot puts the sprite at y=${bottomLeft.y.toFixed(0)} and a top-right one at `
+ + `y=${topRight.y.toFixed(0)} — a bottom-left pivot must hold the sprite ABOVE the entity (a smaller `
+ + 'png y), so the grid rows would move a sprite the wrong way',
+ );
+ // The shifts are a full width and a full height, so their RATIO is the sprite's 2:1
+ // aspect at any viewport zoom. An absolute pixel threshold only pins this machine's
+ // zoom, and would go green for a crossed axis on another.
+ if (shiftX > 0 && shiftY > 0) {
+ const aspect = shiftX / shiftY;
+ check(
+ aspect > 1.5 && aspect < 2.5,
+ `the pivot moved the sprite ${shiftX.toFixed(0)}px across and ${shiftY.toFixed(0)}px down — a ratio `
+ + `of ${aspect.toFixed(2)} where the sprite's own 200×100 makes it 2, so an axis is crossed`,
+ );
+ }
+ return check.failures;
+}
diff --git a/desktop/src/engine/SceneQuery.ts b/desktop/src/engine/SceneQuery.ts
index 9a5c07eb0..f38dc4611 100644
--- a/desktop/src/engine/SceneQuery.ts
+++ b/desktop/src/engine/SceneQuery.ts
@@ -159,6 +159,12 @@ export function buildMultiInspector(
return !datas.every((d) => deepEqual(axisOf(d[f.key], i), p));
});
if (axes.some(Boolean)) { f.mixed = true; f.mixedAxes = axes; }
+ // A pixel view needs the selection to agree on the denominator: 32px is a
+ // different fraction per differently-sized sprite, and one write carries one
+ // fraction — so drop it rather than fan out the primary's arithmetic.
+ if (f.normalizedOf && !datas.every((d) => deepEqual(d[f.normalizedOf!.key], datas[0][f.normalizedOf!.key]))) {
+ delete f.normalizedOf;
+ }
} else if (!datas.every((d) => deepEqual(d[f.key], datas[0][f.key]))) {
f.mixed = true;
}
diff --git a/desktop/src/engine/schema.ts b/desktop/src/engine/schema.ts
index 6f13c43fb..b5cf24bbf 100644
--- a/desktop/src/engine/schema.ts
+++ b/desktop/src/engine/schema.ts
@@ -2,7 +2,7 @@
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
import { getComponentRegistry, getUserComponents, getComponent, getComponentAssetFieldDescriptors, getComponentSkeletalFieldDescriptor, getComponentFieldMeta, Light2DType, usesStagger, isHexOrientation } from 'esengine';
import type { App, SceneData } from 'esengine';
-import type { NodeKind, EntityId, InspectorField, EnumOption, GradientValue, CurveValue } from '@/types';
+import type { NodeKind, EntityId, InspectorField, InspectorFieldValue, EnumOption, GradientValue, CurveValue } from '@/types';
import { t } from '@/i18n';
type SceneEntityLike = SceneData['entities'][number];
@@ -283,6 +283,9 @@ export interface UserFieldMeta {
step?: number;
slider?: boolean;
unit?: string;
+ /** This field is a fraction of the named sibling, axis-wise (Sprite.pivot of Sprite.size)
+ * — the editor can then offer a pixel view; the stored value stays the fraction. */
+ normalizedOf?: string;
advanced?: boolean;
category?: string;
/** Hover help (UE ToolTip). */
@@ -412,6 +415,7 @@ export function fieldMetaFor(compType: string, key: string): UserFieldMeta | nul
step: fromDef.step,
slider: fromDef.slider,
unit: fromDef.unit,
+ normalizedOf: fromDef.normalizedOf,
advanced: fromDef.advanced,
category: fromDef.category,
tooltip: fromDef.tooltip,
@@ -628,6 +632,26 @@ function bitmaskOptions(meta: { bits?: number; source?: string }): EnumOption[]
return Array.from({ length: bits }, (_, i) => ({ label: `Layer ${i}`, value: 1 << i }));
}
+/**
+ * The per-axis denominator behind a `normalizedOf` field, read from the sibling it
+ * names — `Sprite.pivot` × `Sprite.size` is the pivot in pixels. Only a denominator
+ * finite and non-zero on EVERY axis qualifies; anything else has no pixel view, and
+ * a unit whose numbers are all NaN is worse than no unit.
+ */
+function normalizedDenominator(
+ meta: UserFieldMeta | null,
+ value: InspectorFieldValue,
+ data: Readonly<Record<string, unknown>>,
+): { key: string; denom: number[] } | undefined {
+ const key = meta?.normalizedOf;
+ if (!key || !Array.isArray(value)) return undefined;
+ const sibling = data[key];
+ if (!sibling || typeof sibling !== 'object') return undefined;
+ const axes = ['x', 'y', 'z', 'w'] as const;
+ const denom = value.map((_, i) => Number((sibling as Record<string, unknown>)[axes[i]]));
+ return denom.every((n) => Number.isFinite(n) && n !== 0) ? { key, denom } : undefined;
+}
+
/**
* Build one inspector field: an **asset control** for asset-ref fields (carrying
* the `@uuid:` ref or 0 for none), else a value-shape-inferred control.
@@ -693,6 +717,10 @@ function fieldFor(
}
// Presentation policy that applies to any field type (folds, category, help text,
// and a DisplayName override of the key-derived label).
+ if (field) {
+ const norm = normalizedDenominator(meta, field.value, data);
+ if (norm) field.normalizedOf = norm;
+ }
if (field && (meta?.advanced || isAdvancedField(compType, key))) field.advanced = true;
if (field && meta?.category) field.category = meta.category;
if (field && meta?.tooltip) field.tooltip = meta.tooltip;
diff --git a/desktop/src/i18n/messages/details.ts b/desktop/src/i18n/messages/details.ts
index 1fd3f025e..35a0ba902 100644
--- a/desktop/src/i18n/messages/details.ts
+++ b/desktop/src/i18n/messages/details.ts
@@ -41,6 +41,7 @@ export const detailsMessages = defineMessages({
'det.everything': { en: 'Everything', zh: '全部' },
'det.nothing': { en: 'Nothing', zh: '清空' },
'det.unitAria': { en: 'unit', zh: '单位' },
+ 'det.unitFraction': { en: 'frac', zh: '比例' },
'det.removeStop': { en: 'Remove stop', zh: '移除色标' },
'det.removeKey': { en: 'Remove key', zh: '移除关键点' },
'det.wrongAssetType': { en: 'This field only accepts {type} assets', zh: '此字段只接受 {type} 资产' },
@@ -70,6 +71,7 @@ export const detailsMessages = defineMessages({
'det.positionModeAria': { en: 'Position mode', zh: '定位模式' },
'det.inLayout': { en: 'In Layout', zh: '布局内' },
'det.absolute': { en: 'Absolute', zh: '绝对定位' },
+ 'det.pivotPresets': { en: 'Pivot presets', zh: '轴心预设' },
'det.anchor': { en: 'Anchor', zh: '锚点' },
'det.anchorCustom': { en: 'Custom', zh: '自定义' },
'det.horizontal': { en: 'Horizontal', zh: '水平' },
diff --git a/desktop/src/panels/Details.tsx b/desktop/src/panels/Details.tsx
index 48ebe3de5..62bcab779 100644
--- a/desktop/src/panels/Details.tsx
+++ b/desktop/src/panels/Details.tsx
@@ -52,6 +52,7 @@ import { usePrefabConflicts } from '@/store/prefabConflicts';
import { useEditorStore } from '@/store/editorStore';
import { useControllerStore } from '@/store/controllerStore';
import { useInspectorCollapse, isSectionCollapsed } from '@/store/inspectorCollapse';
+import { useFieldUnits, fieldUnitKey, fieldUnitOf } from '@/store/fieldUnits';
import { controllerCurrentPage, drivenField, readComponentData, readModelField, readGearBindings } from '@/controller/controllerModel';
import { useOutliner } from '@/outliner/OutlinerController';
import { isFolderUnder, folderName } from '@/outliner/folders';
@@ -162,8 +163,9 @@ const KIND_LABEL: Record<NodeKind, string> = {
import {
VecControl, SidesControl, EnumControl, EntityControl, FlagsControl, SliderControl, BoolControl, DimControl, StringControl, MapControl, GradientControl, CurveControl, AssetControl,
+ type PixelView,
} from './inspector/controls';
-import { decoratorAction, decoratorExtra, decoratorOwnedFields, entityDecorators } from './inspector/componentDecorators';
+import { decoratorAction, decoratorExtra, decoratorFieldExtra, decoratorOwnedFields, entityDecorators } from './inspector/componentDecorators';
// A field write override (the live "Game" inspector routes edits to the realm
// instead of the undoable SceneCommands path). When set, gestures are no-ops.
@@ -382,7 +384,7 @@ function drivenFieldValue(
return patched ? { ...field, value: patched.value } : field;
}
-function FieldRow({ entities, comp, field: rawField, write }: { entities: EntityId[]; comp: string; field: InspectorField; write?: FieldWrite }) {
+function FieldRow({ entities, comp, field: rawField, write, extra }: { entities: EntityId[]; comp: string; field: InspectorField; write?: FieldWrite; extra?: ReactNode }) {
const field = drivenFieldValue(entities, comp, rawField, write);
const mixed = field.mixed === true;
const { apply, begin, end, cancel } = fieldWriter(entities, comp, field, write);
@@ -399,6 +401,16 @@ function FieldRow({ entities, comp, field: rawField, write }: { entities: Entity
max: field.max,
});
+ // The pixel view of a fraction-of-a-sibling field (Sprite.pivot of Sprite.size).
+ // The row owns the unit CHOICE — a persisted editor preference, never scene data —
+ // and hands the control only the numbers it needs to show and undo the maths.
+ const unitKey = fieldUnitKey(comp, field.key);
+ const units = useFieldUnits((s) => s.units);
+ const setUnit = useFieldUnits((s) => s.set);
+ const pixels: PixelView | undefined = field.normalizedOf
+ ? { denom: field.normalizedOf.denom, unit: fieldUnitOf(units, unitKey), onUnit: (u) => setUnit(unitKey, u) }
+ : undefined;
+
// A fixed set of string choices declared on the field itself (an importer's
// compression format). Choices that depend on the scene — a spine animation, a
// dragonBones armature, an i18n key — are an `enum` with name-valued options
@@ -452,7 +464,7 @@ function FieldRow({ entities, comp, field: rawField, write }: { entities: Entity
case 'vec2':
case 'vec3':
case 'vec4':
- control = <VecControl value={field.value as number[]} mixed={mixed} mixedAxes={field.mixedAxes} onBegin={begin} onEnd={end} onCancel={cancel} onChange={apply} />;
+ control = <VecControl value={field.value as number[]} mixed={mixed} mixedAxes={field.mixedAxes} pixels={pixels} onBegin={begin} onEnd={end} onCancel={cancel} onChange={apply} />;
break;
case 'dimension':
control = <DimControl value={field.value as DimensionValue} mixed={mixed} onBegin={begin} onEnd={end} onChange={apply} />;
@@ -545,6 +557,7 @@ function FieldRow({ entities, comp, field: rawField, write }: { entities: Entity
const invalid = !!field.required && isRequiredEmpty(field.value);
return (
+ <>
<div
className={`prop${modified ? ' modified' : ''}${mixed ? ' mixed' : ''}${invalid ? ' invalid' : ''}`}
onContextMenu={
@@ -605,6 +618,8 @@ function FieldRow({ entities, comp, field: rawField, write }: { entities: Entity
/>
)}
</div>
+ {extra && <div className="prop-aside"><div>{extra}</div></div>}
+ </>
);
}
@@ -799,6 +814,7 @@ function ComponentSection({
write,
action,
extra,
+ fieldExtra,
hideFields,
}: {
entities: EntityId[];
@@ -809,6 +825,8 @@ function ComponentSection({
write?: FieldWrite;
action?: { label: string; title: string; run: () => void };
extra?: React.ReactNode;
+ /** Per-field extra UI, rendered under that field's own row (Sprite.pivot's presets). */
+ fieldExtra?: (field: InspectorField) => React.ReactNode;
/** Field keys the `extra` block owns (e.g. UINode's Layout section), skipped by
* the generic field flow so they aren't edited in two places. */
hideFields?: ReadonlySet<string>;
@@ -844,7 +862,7 @@ function ComponentSection({
else if (f.advanced) advancedFields.push(f);
else ungrouped.push(f);
}
- const row = (f: InspectorField) => <FieldRow key={f.key} entities={entities} comp={comp.name} field={f} write={write} />;
+ const row = (f: InspectorField) => <FieldRow key={f.key} entities={entities} comp={comp.name} field={f} write={write} extra={fieldExtra?.(f)} />;
const enable = comp.enable;
// The promoted enable field is hidden from the body, so it gets its gear dot
// here — page-driven show/hide is the most common boolean gear.
@@ -1003,6 +1021,7 @@ function GameDetails() {
onToggle={() => toggle(comp.name)}
action={decoratorAction(ctx)}
extra={decoratorExtra(ctx)}
+ fieldExtra={(f) => decoratorFieldExtra({ ...ctx, field: f })}
hideFields={decoratorOwnedFields(ctx)}
write={(key, type, value) =>
PlayInspect.setField(selection, comp.name, key, toModelValue(compData(comp.name), type, key, value as never))
@@ -2406,6 +2425,7 @@ function EditorDetails() {
onMore={(e, name) => setCompMenu({ x: e.clientX, y: e.clientY, comp: name })}
action={decoratorAction(ctx)}
extra={decoratorExtra(ctx)}
+ fieldExtra={(f) => decoratorFieldExtra({ ...ctx, field: f })}
hideFields={decoratorOwnedFields(ctx)}
/>
);
diff --git a/desktop/src/panels/inspector/componentDecorators.tsx b/desktop/src/panels/inspector/componentDecorators.tsx
index 8ab9f68e6..cc970a0da 100644
--- a/desktop/src/panels/inspector/componentDecorators.tsx
+++ b/desktop/src/panels/inspector/componentDecorators.tsx
@@ -35,7 +35,7 @@ import {
DimensionUnit, AnchorAxis, detectAnchorAxes, UIPositionType, FlexDirection,
FlexWrap, JustifyContent, AlignItems, INTERACTION_CONTROLLER, INTERACTION_PAGES,
} from 'esengine';
-import type { InspectorComponent, EntityId } from '@/types';
+import type { InspectorComponent, InspectorField, EntityId } from '@/types';
async function addTextLayoutBox(sourceId: EntityId): Promise<void> {
let canvas = SceneCommands.findCanvas();
@@ -436,6 +436,41 @@ function FlexLayoutControl({ entities, comp }: { entities: EntityId[]; comp: Ins
);
}
+// The nine pivot presets, as the fraction each grid cell writes. Columns are
+// left/centre/right; rows read top→bottom while pivot Y runs bottom-up (0 = bottom),
+// so row 0 is Y 1. Values a click can produce — every other pivot is "Custom".
+const PIVOT_X = [0, 0.5, 1];
+const PIVOT_Y = [1, 0.5, 0];
+
+/** The pivot picker under Sprite.pivot: one click for the nine presets a sprite is
+ * almost always pivoted at, so the common case needs no arithmetic in either unit.
+ * The numeric row stays — pivot is continuous, and a preset is only a shortcut into
+ * it (as with UINode anchors, the fields remain the single source of truth). */
+function PivotPicker({ entities, field }: { entities: EntityId[]; field: InspectorField }) {
+ const [x, y] = (field.value as number[]) ?? [0.5, 0.5];
+ const c = PIVOT_X.indexOf(x);
+ const r = PIVOT_Y.indexOf(y);
+ const preset = c >= 0 && r >= 0 && field.mixed !== true;
+ const pick = (col: number, row: number) => {
+ SceneCommands.beginGesture('Pivot');
+ for (const id of entities) SceneCommands.setField(id, 'Sprite', 'pivot', 'vec2', [PIVOT_X[col], PIVOT_Y[row]]);
+ SceneCommands.endGesture();
+ };
+ return (
+ <div className="pivot-pick">
+ <AlignGrid
+ active={preset ? { c, r } : null}
+ ariaLabel={t('det.pivotPresets')}
+ cellTitle={(col, row) => `${ANCHOR_V_LABEL[row]} · ${ANCHOR_H_LABEL[col]}`}
+ onPick={pick}
+ />
+ <em className="pivot-cur">
+ {preset ? `${ANCHOR_V_LABEL[r]} · ${ANCHOR_H_LABEL[c]}` : t('det.anchorCustom')}
+ </em>
+ </div>
+ );
+}
+
// The inline Controllers strip — the panel's per-node authoring brought into the
// inspector so choosing a state page and gearing a field happen in ONE place (no
// cross-panel dance). Reuses the exact model readers + SceneCommands the Controllers
@@ -597,6 +632,21 @@ export interface ComponentDecorator {
action?(ctx: DecoratorContext): { label: string; title: string; run: () => void } | undefined;
}
+/**
+ * Extra UI for ONE FIELD, rendered directly under that field's row — the rung
+ * between a component decorator (whole section) and an entity one (whole entity).
+ * A preset picker belongs beside the numbers it writes, and a component decorator
+ * cannot put it there: its block renders once, above every row in the section.
+ */
+export interface FieldDecorator {
+ id: string;
+ component: string;
+ /** The field key this attaches under. */
+ field: string;
+ surfaces?: readonly InspectorSurface[];
+ render(ctx: DecoratorContext & { field: InspectorField }): ReactNode;
+}
+
/**
* Extra UI for the ENTITY rather than one component, rendered above the sections.
* A separate kind because its trigger is a predicate over the whole component set,
@@ -611,6 +661,7 @@ export interface EntityDecorator {
}
const componentContrib = new ContributionRegistry<ComponentDecorator>('inspector component decorator');
+const fieldContrib = new ContributionRegistry<FieldDecorator>('inspector field decorator');
const entityContrib = new ContributionRegistry<EntityDecorator>('inspector entity decorator');
const serves = (d: { surfaces?: readonly InspectorSurface[] }, surface: InspectorSurface): boolean =>
@@ -649,6 +700,15 @@ const BUILTIN_COMPONENT_DECORATORS: ComponentDecorator[] = [
})),
];
+const BUILTIN_FIELD_DECORATORS: FieldDecorator[] = [
+ {
+ id: 'core.sprite.pivot',
+ component: 'Sprite',
+ field: 'pivot',
+ render: ({ entities, field }) => <PivotPicker entities={entities} field={field} />,
+ },
+];
+
const BUILTIN_ENTITY_DECORATORS: EntityDecorator[] = [
{
id: 'core.ui.controllers',
@@ -658,21 +718,26 @@ const BUILTIN_ENTITY_DECORATORS: EntityDecorator[] = [
];
componentContrib.registerAll('core', BUILTIN_COMPONENT_DECORATORS);
+fieldContrib.registerAll('core', BUILTIN_FIELD_DECORATORS);
entityContrib.registerAll('core', BUILTIN_ENTITY_DECORATORS);
export const decoratorRegistry = {
registerComponent: (owner: Owner, d: ComponentDecorator): Disposable => componentContrib.register(owner, d),
+ registerField: (owner: Owner, d: FieldDecorator): Disposable => fieldContrib.register(owner, d),
registerEntity: (owner: Owner, d: EntityDecorator): Disposable => entityContrib.register(owner, d),
disposeOwner: (owner: Owner): void => {
componentContrib.disposeOwner(owner);
+ fieldContrib.disposeOwner(owner);
entityContrib.disposeOwner(owner);
},
subscribe: (fn: () => void): (() => void) => {
const a = componentContrib.subscribe(fn);
- const b = entityContrib.subscribe(fn);
- return () => { a(); b(); };
+ const b = fieldContrib.subscribe(fn);
+ const c = entityContrib.subscribe(fn);
+ return () => { a(); b(); c(); };
},
- getRevision: (): number => componentContrib.getRevision() + entityContrib.getRevision(),
+ getRevision: (): number =>
+ componentContrib.getRevision() + fieldContrib.getRevision() + entityContrib.getRevision(),
};
/** Decorators attached to one component type on this surface. */
@@ -697,6 +762,15 @@ export function decoratorExtra(ctx: DecoratorContext): ReactNode | undefined {
return <>{parts.map((d) => <Fragment key={d.id}>{d.render!(ctx)}</Fragment>)}</>;
}
+/** The rendered block that sits under one field's row, or undefined when none applies. */
+export function decoratorFieldExtra(ctx: DecoratorContext & { field: InspectorField }): ReactNode | undefined {
+ const parts = fieldContrib.all().filter(
+ (d) => d.component === ctx.comp.name && d.field === ctx.field.key && serves(d, ctx.surface),
+ );
+ if (!parts.length) return undefined;
+ return <>{parts.map((d) => <Fragment key={d.id}>{d.render(ctx)}</Fragment>)}</>;
+}
+
/** Every field key claimed by this component's decorators, or undefined when none is. */
export function decoratorOwnedFields(ctx: DecoratorContext): ReadonlySet<string> | undefined {
const keys = new Set<string>();
diff --git a/desktop/src/panels/inspector/controls.tsx b/desktop/src/panels/inspector/controls.tsx
index bbc8b5257..a20a88b26 100644
--- a/desktop/src/panels/inspector/controls.tsx
+++ b/desktop/src/panels/inspector/controls.tsx
@@ -25,6 +25,7 @@ import { prettyLabel, hexToRgba, coerceEnumInput } from '@/engine/schema';
import { AssetRegistry } from '@/project/AssetRegistry';
import { revealAsset } from '@/project/assetReveal';
import { Toasts } from '@/store/Toasts';
+import type { FieldUnit } from '@/store/fieldUnits';
import { t } from '@/i18n';
import { DimensionUnit, INVALID_ENTITY } from 'esengine';
import type {
@@ -100,18 +101,33 @@ function VecField({
);
}
+/** The pixel view of a normalized vector (`field.normalizedOf` resolved): the sibling's
+ * per-axis value as the denominator, plus the unit the row is currently in and how to
+ * change it. The caller owns that choice — a control writes values, not preferences. */
+export interface PixelView {
+ denom: number[];
+ unit: FieldUnit;
+ onUnit: (u: FieldUnit) => void;
+}
+
export function VecControl({
value,
mixed,
mixedAxes,
+ pixels,
onBegin,
onEnd,
onCancel,
onChange,
-}: ControlGesture & { value: number[]; mixed?: boolean; mixedAxes?: boolean[]; onChange: (v: number[]) => void }) {
+}: ControlGesture & { value: number[]; mixed?: boolean; mixedAxes?: boolean[]; pixels?: PixelView; onChange: (v: number[]) => void }) {
+ // In px the wells show — and SCRUB IN — the multiplied-out value, so a drag moves
+ // by pixels; only the commit divides back. The fraction is what reaches the model
+ // either way: the unit never changes what is stored.
+ const px = pixels?.unit === 'px';
+ const shown = px ? value.map((n, i) => n * pixels!.denom[i]) : value;
return (
- <div className="vec">
- {value.map((n, i) => (
+ <div className={`vec${pixels ? ' vec-normalized' : ''}`}>
+ {shown.map((n, i) => (
<VecField
key={i}
axis={AXES[i]}
@@ -127,11 +143,25 @@ export function VecControl({
// to keep each (possibly multi-selected) entity's own value there,
// instead of stamping the primary's whole vector onto the selection.
const next = value.map(() => NaN);
- next[i] = v;
+ next[i] = px ? v / pixels!.denom[i] : v;
onChange(next);
}}
/>
))}
+ {pixels && (
+ <span className="field dropdown vec-unit">
+ <Select
+ variant="field"
+ value={pixels.unit}
+ ariaLabel={t('det.unitAria')}
+ options={[
+ { value: 'norm', label: t('det.unitFraction') },
+ { value: 'px', label: 'px' },
+ ]}
+ onChange={(v) => pixels.onUnit(v as FieldUnit)}
+ />
+ </span>
+ )}
</div>
);
}
diff --git a/desktop/src/store/fieldUnits.ts b/desktop/src/store/fieldUnits.ts
new file mode 100644
index 000000000..1cc413247
--- /dev/null
+++ b/desktop/src/store/fieldUnits.ts
@@ -0,0 +1,57 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file fieldUnits.ts — which unit a `normalizedOf` field is shown in, keyed by
+ * `Component.field`, persisted like the inspector's collapse state.
+ *
+ * The unit is a VIEW, never data: the scene always stores the fraction, and this
+ * store only decides whether the row renders it as a fraction or multiplied out
+ * into pixels. Persisting it is what makes the choice worth offering — a creator
+ * who thinks in pixels sets it once instead of on every reselect.
+ */
+import { create } from 'zustand';
+
+/** How a normalized field renders: as the stored fraction, or multiplied into pixels. */
+export type FieldUnit = 'norm' | 'px';
+
+const LS_KEY = 'estella.fieldUnits';
+
+function load(): Record<string, FieldUnit> {
+ if (typeof localStorage === 'undefined') return {};
+ try {
+ return JSON.parse(localStorage.getItem(LS_KEY) ?? '{}') as Record<string, FieldUnit>;
+ } catch {
+ return {}; // corrupt blob → start clean
+ }
+}
+function save(units: Record<string, FieldUnit>): void {
+ if (typeof localStorage === 'undefined') return;
+ try {
+ localStorage.setItem(LS_KEY, JSON.stringify(units));
+ } catch {
+ /* quota / private mode — persistence is best-effort */
+ }
+}
+
+/** The store key for one field: the component it belongs to plus its name. */
+export const fieldUnitKey = (comp: string, key: string): string => `${comp}.${key}`;
+
+interface FieldUnitState {
+ units: Record<string, FieldUnit>;
+ set: (key: string, unit: FieldUnit) => void;
+}
+
+export const useFieldUnits = create<FieldUnitState>((set, get) => ({
+ units: load(),
+ set: (key, unit) =>
+ set(() => {
+ const units = { ...get().units, [key]: unit };
+ save(units);
+ return { units };
+ }),
+}));
+
+/** The unit a field renders in — the user's choice, else the stored fraction. */
+export function fieldUnitOf(units: Record<string, FieldUnit>, key: string): FieldUnit {
+ return units[key] ?? 'norm';
+}
diff --git a/desktop/src/theme/inspector.css b/desktop/src/theme/inspector.css
index e2d31b541..e2d1a5c91 100644
--- a/desktop/src/theme/inspector.css
+++ b/desktop/src/theme/inspector.css
@@ -158,6 +158,12 @@
/* property rows (label col + value col, reset on right) */
.prop { display: grid; grid-template-columns: 38% 1fr 18px; align-items: center; gap: 4px; min-height: var(--h-prop); padding: 1px 0; position: relative; }
+/* A field decorator's block (FieldDecorator), on the same track grid as its row so it
+ lines up under the value wells rather than under the label. */
+.prop-aside { display: grid; grid-template-columns: 38% 1fr 18px; gap: 4px; padding: 2px 0 4px; }
+.prop-aside > * { grid-column: 2; }
+.pivot-pick { display: flex; align-items: center; gap: 9px; }
+.pivot-pick .pivot-cur { font-style: normal; font-size: var(--fs-sm); font-weight: 600; color: var(--acc-hi); }
.prop-label { font-size: var(--fs-sm); color: var(--text-dim); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; padding-left: 2px; }
.prop-label.scrub { cursor: ew-resize; user-select: none; }
.prop-label.scrub:hover { color: var(--text); }
@@ -189,6 +195,9 @@
track count resolves from min-content there — so plain flex wrap it is). */
.vec { display: flex; flex-wrap: wrap; gap: 4px; flex: 1; min-width: 0; }
.vec .vfield { flex: 1 1 56px; }
+/* A fraction-of-a-sibling vector (Sprite.pivot) carries a frac/px unit picker, capped
+ like DimControl's so its width:100% trigger can't crush the axis wells. */
+.vec .field.vec-unit { flex: 0 0 54px; }
.vfield { height: 22px; display: flex; align-items: center; background: var(--inset); border: 1px solid var(--border); border-radius: var(--r-sm); overflow: hidden; min-width: 0; transition: border-color var(--t-fast), box-shadow var(--t-fast); }
.vfield:focus-within { border-color: var(--acc); box-shadow: 0 0 0 2px var(--acc-soft); }
.ax { width: 16px; height: 100%; display: grid; place-items: center; font-size: var(--fs-3xs); font-weight: 700; font-family: var(--mono); color: var(--on-accent); cursor: ew-resize; flex-shrink: 0; font-style: normal; }
diff --git a/desktop/src/types.ts b/desktop/src/types.ts
index ca9c6fa84..2efd86ba8 100644
--- a/desktop/src/types.ts
+++ b/desktop/src/types.ts
@@ -155,6 +155,13 @@ export interface InspectorField {
slider?: boolean;
/** Unit shown after the resting value (e.g. '°', 'px'). */
unit?: string;
+ /**
+ * This vector is a fraction of the sibling field `key`, whose current per-axis
+ * value is `denom` — so the row can offer a pixel view (`value[i] * denom[i]`)
+ * of a number the data keeps normalized. Resolved only when every axis of the
+ * denominator is finite and non-zero; absent means there is no pixel view.
+ */
+ normalizedOf?: { key: string; denom: number[] };
/** A rarely-edited field — tucked behind the component's "Advanced" fold. */
advanced?: boolean;
/** Groups the field under a collapsible category header (UE's property categories). */
diff --git a/docs/astro/src/data/components.generated.json b/docs/astro/src/data/components.generated.json
index 2dad778c6..b9a9ce22c 100644
--- a/docs/astro/src/data/components.generated.json
+++ b/docs/astro/src/data/components.generated.json
@@ -2643,8 +2643,7 @@
"key": "pivot",
"type": "Vec2",
"default": "(0.5, 0.5)",
- "doc": "Anchor point (0–1) the sprite rotates and scales about.",
- "advanced": true
+ "doc": "Anchor point the sprite rotates and scales about, as a fraction of its size (0.5,0.5 = centre). Values outside 0–1 sit off the sprite."
},
{
"key": "uvOffset",
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index 1a32b610f..1d7995dce 100644
--- a/sdk/etc/index.api.md
+++ b/sdk/etc/index.api.md
@@ -2758,6 +2758,7 @@ label: string | undefined
map: boolean | undefined
max: number | undefined
min: number | undefined
+normalizedOf: string | 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 ed80b0fd5..825075d6a 100644
--- a/sdk/etc/index.native.api.md
+++ b/sdk/etc/index.native.api.md
@@ -2766,6 +2766,7 @@ label: string | undefined
map: boolean | undefined
max: number | undefined
min: number | undefined
+normalizedOf: string | 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 4e77804d2..236381408 100644
--- a/sdk/etc/index.node.api.md
+++ b/sdk/etc/index.node.api.md
@@ -2753,6 +2753,7 @@ label: string | undefined
map: boolean | undefined
max: number | undefined
min: number | undefined
+normalizedOf: string | 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 f3374c45e..c35377fc6 100644
--- a/sdk/etc/minigame.api.md
+++ b/sdk/etc/minigame.api.md
@@ -2753,6 +2753,7 @@ label: string | undefined
map: boolean | undefined
max: number | undefined
min: number | undefined
+normalizedOf: string | 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 5940b81e1..afb7ec466 100644
--- a/sdk/etc/wechat.api.md
+++ b/sdk/etc/wechat.api.md
@@ -2753,6 +2753,7 @@ label: string | undefined
map: boolean | undefined
max: number | undefined
min: number | undefined
+normalizedOf: string | 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 3d1a0be92..3593ed589 100644
--- a/sdk/src/ecs/component.generated.ts
+++ b/sdk/src/ecs/component.generated.ts
@@ -635,7 +635,7 @@ export const COMPONENT_META: Record<string, ComponentMetaEntry> = {
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 },
+ pivot: { tooltip: "Anchor point the sprite rotates and scales about, as a fraction of its size (0.5,0.5 = centre). Values outside 0–1 sit off the sprite.", normalizedOf: "size" },
uvOffset: { advanced: true },
uvScale: { advanced: true },
layer: { step: 1, tooltip: "Sorting layer — controls draw order across sprites.", enumSource: "sortingLayers" },
diff --git a/sdk/src/ecs/component.ts b/sdk/src/ecs/component.ts
index ebdb17d18..587c8bf93 100644
--- a/sdk/src/ecs/component.ts
+++ b/sdk/src/ecs/component.ts
@@ -92,6 +92,12 @@ export interface FieldMeta {
slider?: boolean;
/** Unit shown after the resting value (e.g. '°', 'px', '%'). */
unit?: string;
+ /**
+ * This field is a fraction of the named sibling, axis-wise (`Sprite.pivot` of
+ * `Sprite.size`), so the editor can offer a pixel view of it. The stored value
+ * stays the fraction. Authored `normalized_of=` at the C++ ES_PROPERTY site.
+ */
+ normalizedOf?: string;
/** Human label / tooltip overriding the key-derived ones. */
label?: string;
tooltip?: string;
diff --git a/sdk/tests/__snapshots__/component-fieldmeta-golden.test.ts.snap b/sdk/tests/__snapshots__/component-fieldmeta-golden.test.ts.snap
index 3ff146cdf..fc3d65b3b 100644
--- a/sdk/tests/__snapshots__/component-fieldmeta-golden.test.ts.snap
+++ b/sdk/tests/__snapshots__/component-fieldmeta-golden.test.ts.snap
@@ -688,8 +688,8 @@ exports[`builtin FieldMeta (RC9-1 equivalence gate) > matches the golden snapsho
"tooltip": "Parallax scroll factor (1 = with world, <1 = slower, 0 = locked to camera).",
},
"pivot": {
- "advanced": true,
- "tooltip": "Anchor point (0–1) the sprite rotates and scales about.",
+ "normalizedOf": "size",
+ "tooltip": "Anchor point the sprite rotates and scales about, as a fraction of its size (0.5,0.5 = centre). Values outside 0–1 sit off the sprite.",
},
"tileSize": {
"advanced": true,
diff --git a/src/esengine/bindings/EditorAPI.generated.cpp b/src/esengine/bindings/EditorAPI.generated.cpp
index e1114a41f..fbc6d6082 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 473e118839306c3d
+ * @schema_hash 38c95ef984c14e01
*/
-#define ES_EDITOR_API_SCHEMA_HASH "473e118839306c3d"
+#define ES_EDITOR_API_SCHEMA_HASH "38c95ef984c14e01"
#include <emscripten/bind.h>
#include <string>
diff --git a/src/esengine/core/Reflection.hpp b/src/esengine/core/Reflection.hpp
index b97c0262b..08abd79da 100644
--- a/src/esengine/core/Reflection.hpp
+++ b/src/esengine/core/Reflection.hpp
@@ -73,6 +73,8 @@
* - category=<s> : inspector group header
* - advanced : tuck behind an "advanced" fold
* - enum_source=<name> / bitmask_source=<name> : editor-resolved option/label source
+ * - normalized_of=<field> : this value is a fraction of that sibling (same
+ * type), so the editor can offer a pixel view of it
*
* Serialization / runtime policy:
* - invalidates=<field> : after an editor set, flip <field> so the owning
@@ -81,7 +83,8 @@
* - 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.
+ * invalidates=/normalized_of= naming no field) is a hard EHT error, not a
+ * silent drop.
*
* Examples:
* ES_PROPERTY(asset=texture)
diff --git a/src/esengine/ecs/components/Sprite.hpp b/src/esengine/ecs/components/Sprite.hpp
index 9ba726196..d8636fc13 100644
--- a/src/esengine/ecs/components/Sprite.hpp
+++ b/src/esengine/ecs/components/Sprite.hpp
@@ -58,7 +58,7 @@ 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(advanced, tooltip="Anchor point (0–1) the sprite rotates and scales about.")
+ ES_PROPERTY(normalized_of=size, tooltip="Anchor point the sprite rotates and scales about, as a fraction of its size (0.5,0.5 = centre). Values outside 0–1 sit off the sprite.")
glm::vec2 pivot{0.5f, 0.5f};
/** @brief UV coordinate offset for sprite sheets */
diff --git a/tools/eht/generators/metadata.py b/tools/eht/generators/metadata.py
index d5c7dbfe9..c7078bd79 100644
--- a/tools/eht/generators/metadata.py
+++ b/tools/eht/generators/metadata.py
@@ -113,6 +113,8 @@ class MetadataGenerator:
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 'normalized_of' in a:
+ entries.append(('normalizedOf', json.dumps(a['normalized_of'], ensure_ascii=False)))
if entries:
out.append((prop.name, entries))
return out
diff --git a/tools/eht/parser.py b/tools/eht/parser.py
index 6a7b0567e..3b7d274c7 100644
--- a/tools/eht/parser.py
+++ b/tools/eht/parser.py
@@ -63,6 +63,11 @@ class CppParser:
# Same value grammar as a C++ member initializer: number, true/false,
# Enum::Member, or a braced vector `{100, 100}`.
'editor_default',
+ # `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
+ # sibling is the denominator, never a second source of truth.
+ 'normalized_of',
})
NUMERIC_ANNOTATIONS = frozenset({'min', 'max', 'step'})
@@ -241,16 +246,28 @@ class CppParser:
)
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}
+ """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
+ 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)."""
+ 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 field_names:
+ if target is not None and target not in by_name:
+ self.errors.append(f"{loc}: invalidates='{target}' names no field on this component")
+ denom = prop.annotations.get('normalized_of')
+ if denom is None:
+ continue
+ if denom == prop.name:
+ self.errors.append(f"{loc}: normalized_of='{denom}' is the field itself")
+ elif denom not in by_name:
+ self.errors.append(f"{loc}: normalized_of='{denom}' names no field on this component")
+ elif by_name[denom].cpp_type != prop.cpp_type:
self.errors.append(
- f"{filepath}:{component.name}.{prop.name}: "
- f"invalidates='{target}' names no field on this component"
+ f"{loc}: normalized_of='{denom}' is {by_name[denom].cpp_type}, "
+ f"not {prop.cpp_type}"
)
@staticmethod