Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

refactor: extract StateMachine asset handling into StateMachineAssets module

esengine943e03329515
diff --git a/editor/src/panels/state-machine-graph/GraphDetailPanel.ts b/editor/src/panels/state-machine-graph/GraphDetailPanel.ts
index 849f1df18..46066bdc2 100644
--- a/editor/src/panels/state-machine-graph/GraphDetailPanel.ts
+++ b/editor/src/panels/state-machine-graph/GraphDetailPanel.ts
@@ -3,6 +3,9 @@ const CHEVRON_DOWN_SVG = `<svg width="12" height="12" viewBox="0 0 24 24" fill="
const CLOSE_SVG = `<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="15 6 9 12 15 18"></polyline></svg>`;
const REMOVE_SVG = `<svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="18" y1="6" x2="6" y2="18"></line><line x1="6" y1="6" x2="18" y2="18"></line></svg>`;
+import { showAssetPicker } from '../../ui/asset-picker';
+import { isAssetField, getAssetDisplayPath, IMAGE_EXTENSIONS } from '../../utils/smAssetUtils';
+
const EASING_OPTIONS = ['linear', 'easeInQuad', 'easeOutQuad', 'easeInOutQuad', 'easeInCubic', 'easeOutCubic', 'easeInOutCubic', 'easeInBack', 'easeOutBack', 'easeInOutBack', 'easeOutBounce'];
const COMPARATOR_OPTIONS = ['eq', 'neq', 'gt', 'lt', 'gte', 'lte'];
const COMPARATOR_LABELS: Record<string, string> = { eq: '=', neq: '\u2260', gt: '>', lt: '<', gte: '\u2265', lte: '\u2264' };
@@ -274,21 +277,32 @@ export class GraphDetailPanel {
}
});
- const valInput = document.createElement('input');
- valInput.className = 'es-input';
- valInput.style.cssText = 'width:64px;flex-shrink:0;font-size:11px;padding:2px 4px;height:20px;';
- valInput.value = String(value ?? '');
- valInput.addEventListener('change', () => {
- this.callbacks_.onPropertyValueChanged(stateName, key, parsePropertyValue(valInput.value));
- });
+ if (isAssetField(key)) {
+ const assetEditor = this.createAssetValueEditor(
+ getAssetDisplayPath(value),
+ (assetValue) => {
+ this.callbacks_.onPropertyValueChanged(stateName, key, assetValue);
+ },
+ );
+ row.appendChild(keyInput);
+ row.appendChild(assetEditor);
+ } else {
+ const valInput = document.createElement('input');
+ valInput.className = 'es-input';
+ valInput.style.cssText = 'width:64px;flex-shrink:0;font-size:11px;padding:2px 4px;height:20px;';
+ valInput.value = String(value ?? '');
+ valInput.addEventListener('change', () => {
+ this.callbacks_.onPropertyValueChanged(stateName, key, parsePropertyValue(valInput.value));
+ });
+ row.appendChild(keyInput);
+ row.appendChild(valInput);
+ }
const removeBtn = this.createRemoveBtn();
removeBtn.addEventListener('click', () => {
this.callbacks_.onRemoveProperty(stateName, key);
});
- row.appendChild(keyInput);
- row.appendChild(valInput);
row.appendChild(removeBtn);
container.appendChild(row);
}
@@ -428,17 +442,29 @@ export class GraphDetailPanel {
keyEl.style.cssText = 'flex:1;min-width:0;font-size:10px;color:var(--es-text-secondary, #aaa);overflow:hidden;text-overflow:ellipsis;white-space:nowrap;';
keyEl.textContent = key;
- const valInput = document.createElement('input');
- valInput.className = 'es-input';
- valInput.style.cssText = 'width:50px;flex-shrink:0;font-size:10px;padding:1px 4px;height:18px;';
- valInput.value = String(value ?? '');
- valInput.addEventListener('change', () => {
- const newProps = { ...(entry.properties ?? {}), [key]: parsePropertyValue(valInput.value) };
- this.callbacks_.onUpdateBlendEntry?.(stateName, entryIndex, 'properties', newProps);
- });
-
propRow.appendChild(keyEl);
- propRow.appendChild(valInput);
+
+ if (isAssetField(key)) {
+ const assetEditor = this.createAssetValueEditor(
+ getAssetDisplayPath(value),
+ (assetValue: string) => {
+ const newProps = { ...(entry.properties ?? {}), [key]: assetValue || undefined };
+ this.callbacks_.onUpdateBlendEntry?.(stateName, entryIndex, 'properties', newProps);
+ },
+ );
+ propRow.appendChild(assetEditor);
+ } else {
+ const valInput = document.createElement('input');
+ valInput.className = 'es-input';
+ valInput.style.cssText = 'width:50px;flex-shrink:0;font-size:10px;padding:1px 4px;height:18px;';
+ valInput.value = String(value ?? '');
+ valInput.addEventListener('change', () => {
+ const newProps = { ...(entry.properties ?? {}), [key]: parsePropertyValue(valInput.value) };
+ this.callbacks_.onUpdateBlendEntry?.(stateName, entryIndex, 'properties', newProps);
+ });
+ propRow.appendChild(valInput);
+ }
+
container.appendChild(propRow);
}
}
@@ -713,6 +739,52 @@ export class GraphDetailPanel {
return sel;
}
+ private createAssetValueEditor(currentPath: string, onChange: (value: string) => void): HTMLElement {
+ const wrap = document.createElement('div');
+ wrap.style.cssText = 'display:flex;align-items:center;gap:2px;flex-shrink:0;width:100px;';
+
+ const pathEl = document.createElement('input');
+ pathEl.className = 'es-input';
+ pathEl.style.cssText = 'flex:1;min-width:0;font-size:10px;padding:1px 4px;height:20px;';
+ pathEl.readOnly = true;
+ pathEl.value = currentPath;
+ pathEl.title = currentPath || 'No asset selected';
+ wrap.appendChild(pathEl);
+
+ const browseBtn = document.createElement('button');
+ browseBtn.className = 'es-btn es-btn-icon es-btn-clear';
+ browseBtn.style.cssText = 'width:18px;height:18px;padding:0;flex-shrink:0;font-size:10px;';
+ browseBtn.textContent = '...';
+ browseBtn.title = 'Browse asset';
+ browseBtn.addEventListener('click', async () => {
+ const result = await showAssetPicker({
+ title: 'Select Texture',
+ allowedTypes: ['image'],
+ extensions: IMAGE_EXTENSIONS,
+ });
+ if (result) {
+ pathEl.value = result.relativePath;
+ pathEl.title = result.relativePath;
+ onChange(result.relativePath);
+ }
+ });
+ wrap.appendChild(browseBtn);
+
+ const clearBtn = document.createElement('button');
+ clearBtn.className = 'es-btn es-btn-icon es-btn-clear';
+ clearBtn.style.cssText = 'width:18px;height:18px;padding:0;flex-shrink:0;font-size:10px;';
+ clearBtn.textContent = '\u00d7';
+ clearBtn.title = 'Clear';
+ clearBtn.addEventListener('click', () => {
+ pathEl.value = '';
+ pathEl.title = 'No asset selected';
+ onChange('');
+ });
+ wrap.appendChild(clearBtn);
+
+ return wrap;
+ }
+
private createRemoveBtn(): HTMLButtonElement {
const btn = document.createElement('button');
btn.className = 'es-btn es-btn-icon es-btn-clear';
@@ -730,3 +802,5 @@ function parsePropertyValue(raw: string): unknown {
if (!isNaN(num) && raw.trim() !== '') return num;
return raw;
}
+
+
diff --git a/editor/src/property/editors/stateMachineEditor.ts b/editor/src/property/editors/stateMachineEditor.ts
index 716ff22ff..4bd7bd1aa 100644
--- a/editor/src/property/editors/stateMachineEditor.ts
+++ b/editor/src/property/editors/stateMachineEditor.ts
@@ -1,4 +1,6 @@
import type { PropertyEditorContext, PropertyEditorInstance } from '../PropertyEditor';
+import { showAssetPicker } from '../../ui/asset-picker';
+import { isAssetField, getAssetDisplayPath, IMAGE_EXTENSIONS } from '../../utils/smAssetUtils';
interface InputDef {
name: string;
@@ -514,22 +516,74 @@ export function createStateMachineEditor(
keyInput.value = pKey;
keyInput.placeholder = 'Component.field';
- const valInput = document.createElement('input');
- valInput.type = 'text';
- valInput.className = 'es-input es-input-string es-sm-val';
- valInput.value = String(pVal);
-
- const commitProp = () => {
- const newKey = keyInput.value.trim();
- if (!newKey) return;
- if (!state.properties) state.properties = {};
- if (newKey !== pKey) delete state.properties[pKey];
- const raw = valInput.value;
- state.properties[newKey] = raw === 'true' ? true : raw === 'false' ? false : isNaN(Number(raw)) ? raw : Number(raw);
- emit();
- };
- keyInput.addEventListener('change', commitProp);
- valInput.addEventListener('change', commitProp);
+ if (isAssetField(pKey)) {
+ const assetWrap = document.createElement('div');
+ assetWrap.style.cssText = 'display:flex;align-items:center;gap:2px;flex:1;min-width:0;';
+
+ const pathInput = document.createElement('input');
+ pathInput.type = 'text';
+ pathInput.className = 'es-input es-input-string es-sm-val';
+ pathInput.readOnly = true;
+ pathInput.value = getAssetDisplayPath(pVal);
+ pathInput.title = getAssetDisplayPath(pVal) || 'No asset selected';
+
+ const browseBtn = document.createElement('button');
+ browseBtn.className = 'es-btn es-btn-icon es-btn-clear';
+ browseBtn.style.cssText = 'width:20px;height:20px;padding:0;flex-shrink:0;font-size:10px;';
+ browseBtn.textContent = '...';
+ browseBtn.title = 'Browse asset';
+ browseBtn.addEventListener('click', async () => {
+ const result = await showAssetPicker({
+ title: 'Select Texture',
+ allowedTypes: ['image'],
+ extensions: IMAGE_EXTENSIONS,
+ });
+ if (result) {
+ if (!state.properties) state.properties = {};
+ const newKey = keyInput.value.trim() || pKey;
+ if (newKey !== pKey) delete state.properties[pKey];
+ state.properties[newKey] = result.relativePath;
+ pathInput.value = result.relativePath;
+ pathInput.title = result.relativePath;
+ emit();
+ }
+ });
+
+ const clearBtn = document.createElement('button');
+ clearBtn.className = 'es-btn es-btn-icon es-btn-clear';
+ clearBtn.style.cssText = 'width:20px;height:20px;padding:0;flex-shrink:0;font-size:10px;';
+ clearBtn.textContent = '\u00d7';
+ clearBtn.title = 'Clear';
+ clearBtn.addEventListener('click', () => {
+ if (state.properties) delete state.properties[pKey];
+ emit(); rebuild();
+ });
+
+ assetWrap.appendChild(pathInput);
+ assetWrap.appendChild(browseBtn);
+ assetWrap.appendChild(clearBtn);
+ pRow.appendChild(keyInput);
+ pRow.appendChild(assetWrap);
+ } else {
+ const valInput = document.createElement('input');
+ valInput.type = 'text';
+ valInput.className = 'es-input es-input-string es-sm-val';
+ valInput.value = String(pVal);
+
+ const commitProp = () => {
+ const newKey = keyInput.value.trim();
+ if (!newKey) return;
+ if (!state.properties) state.properties = {};
+ if (newKey !== pKey) delete state.properties[pKey];
+ const raw = valInput.value;
+ state.properties[newKey] = raw === 'true' ? true : raw === 'false' ? false : isNaN(Number(raw)) ? raw : Number(raw);
+ emit();
+ };
+ keyInput.addEventListener('change', commitProp);
+ valInput.addEventListener('change', commitProp);
+ pRow.appendChild(keyInput);
+ pRow.appendChild(valInput);
+ }
const rmP = createRemoveBtn();
rmP.addEventListener('click', () => {
@@ -537,8 +591,6 @@ export function createStateMachineEditor(
emit(); rebuild();
});
- pRow.appendChild(keyInput);
- pRow.appendChild(valInput);
pRow.appendChild(rmP);
stateBody.appendChild(pRow);
}
diff --git a/editor/src/utils/smAssetUtils.ts b/editor/src/utils/smAssetUtils.ts
new file mode 100644
index 000000000..ff4cebbe7
--- /dev/null
+++ b/editor/src/utils/smAssetUtils.ts
@@ -0,0 +1,18 @@
+import { getComponentAssetFieldDescriptors } from 'esengine';
+
+export const IMAGE_EXTENSIONS = ['png', 'jpg', 'jpeg', 'webp'];
+
+export function isAssetField(propertyPath: string): boolean {
+ const dotIndex = propertyPath.indexOf('.');
+ if (dotIndex === -1) return false;
+ const componentName = propertyPath.substring(0, dotIndex);
+ const fieldName = propertyPath.substring(dotIndex + 1).split('.')[0];
+ const descriptors = getComponentAssetFieldDescriptors(componentName);
+ return descriptors.some(d => d.field === fieldName && d.type === 'texture');
+}
+
+export function getAssetDisplayPath(value: unknown): string {
+ if (typeof value !== 'string') return '';
+ if (value.startsWith('asset:')) return value.slice(6);
+ return value;
+}
diff --git a/sdk/src/ui/StateMachineAssets.ts b/sdk/src/ui/StateMachineAssets.ts
new file mode 100644
index 000000000..b7b200d3e
--- /dev/null
+++ b/sdk/src/ui/StateMachineAssets.ts
@@ -0,0 +1,80 @@
+import { getComponentAssetFieldDescriptors } from '../scene';
+import type { AssetServer } from '../asset/AssetServer';
+
+const ASSET_PREFIX = 'asset:';
+const assetPathCache_ = new Map<string, boolean>();
+
+export function isAssetPropertyPath(path: string): boolean {
+ const cached = assetPathCache_.get(path);
+ if (cached !== undefined) return cached;
+ const dotIndex = path.indexOf('.');
+ if (dotIndex === -1) { assetPathCache_.set(path, false); return false; }
+ const componentName = path.substring(0, dotIndex);
+ const fieldName = path.substring(dotIndex + 1).split('.')[0];
+ const descriptors = getComponentAssetFieldDescriptors(componentName);
+ const result = descriptors.some(d => d.field === fieldName && d.type === 'texture');
+ assetPathCache_.set(path, result);
+ return result;
+}
+
+export function normalizeAssetValue(value: unknown): string | null {
+ if (typeof value !== 'string') return null;
+ if (value.startsWith(ASSET_PREFIX)) return value.slice(ASSET_PREFIX.length);
+ return value;
+}
+
+export function collectAssetPaths(properties?: Record<string, unknown>): string[] {
+ if (!properties) return [];
+ const paths: string[] = [];
+ for (const [key, value] of Object.entries(properties)) {
+ if (!isAssetPropertyPath(key)) continue;
+ const normalized = normalizeAssetValue(value);
+ if (normalized) paths.push(normalized);
+ }
+ return paths;
+}
+
+export class StateMachineAssetCache {
+ private resolved_ = new Map<string, number>();
+ private loading_ = false;
+ readonly paths: string[];
+
+ constructor(paths: string[]) {
+ const unique = new Set(paths);
+ this.paths = [...unique];
+ }
+
+ get isLoading(): boolean { return this.loading_; }
+
+ get allLoaded(): boolean {
+ return this.paths.length === 0 || this.resolved_.size >= this.paths.length;
+ }
+
+ startLoading(assetServer: AssetServer): void {
+ if (this.loading_) return;
+ this.loading_ = true;
+ let pending = 0;
+ for (const path of this.paths) {
+ if (this.resolved_.has(path)) continue;
+ pending++;
+ assetServer.loadTexture(path).then(info => {
+ this.resolved_.set(path, info.handle);
+ }).catch(() => {}).finally(() => {
+ pending--;
+ if (pending === 0) this.loading_ = false;
+ });
+ }
+ if (pending === 0) this.loading_ = false;
+ }
+
+ getHandle(path: string): number | undefined {
+ return this.resolved_.get(path);
+ }
+
+ release(assetServer: AssetServer): void {
+ for (const path of this.paths) {
+ assetServer.releaseTexture(path);
+ }
+ this.resolved_.clear();
+ }
+}
diff --git a/sdk/src/ui/StateMachinePlugin.ts b/sdk/src/ui/StateMachinePlugin.ts
index 71f3395bb..dce78df37 100644
--- a/sdk/src/ui/StateMachinePlugin.ts
+++ b/sdk/src/ui/StateMachinePlugin.ts
@@ -3,6 +3,7 @@ import { defineSystem, Schedule } from '../system';
import { Res } from '../resource';
import { Time, type TimeData } from '../resource';
import { registerComponent } from '../component';
+import { isEditor, isPlayMode } from '../env';
import type { Entity } from '../types';
import type { World } from '../world';
import { StateMachine } from './StateMachine';
@@ -27,6 +28,13 @@ import {
} from '../timeline/TimelineRuntime';
import type { UploadResult } from '../timeline/TimelineUploader';
import type { ESEngineModule } from '../wasm';
+import { Assets } from '../asset/AssetPlugin';
+import type { AssetServer } from '../asset/AssetServer';
+import { EntityStateMap } from './uiHelpers';
+import {
+ isAssetPropertyPath, normalizeAssetValue, collectAssetPaths,
+ StateMachineAssetCache,
+} from './StateMachineAssets';
const EASING_MAP: Record<string, EasingType> = {
linear: EasingType.Linear,
@@ -52,6 +60,12 @@ const WRAP_MODE_MAP: Record<string, number> = {
const EXIT_STATE = '__exit__';
+interface PropertyContext {
+ world: World;
+ entity: Entity;
+ assets: StateMachineAssetCache;
+}
+
interface LayerRuntime {
currentState: string;
activeTweens: ValueTweenHandle[];
@@ -60,12 +74,14 @@ interface LayerRuntime {
timelinePath: string;
timelineDuration: number;
isExited: boolean;
+ pendingAssetApply: boolean;
}
interface EntityRuntime {
inputs: Map<string, boolean | number>;
layers: LayerRuntime[];
prevHovered: boolean;
+ assets: StateMachineAssetCache;
}
function createInputs(data: StateMachineData): Map<string, boolean | number> {
@@ -91,6 +107,7 @@ function createLayerRuntime(initialState: string): LayerRuntime {
timelinePath: '',
timelineDuration: 0,
isExited: false,
+ pendingAssetApply: true,
};
}
@@ -101,12 +118,31 @@ function getLayers(data: StateMachineData): LayerData[] {
return [{ name: 'Base', states: data.states, initialState: data.initialState }];
}
+function gatherAllAssetPaths(data: StateMachineData): string[] {
+ const paths: string[] = [];
+ const scanStates = (states: Record<string, StateNode>) => {
+ for (const state of Object.values(states)) {
+ paths.push(...collectAssetPaths(state.properties));
+ if (state.blendStates) {
+ for (const entry of state.blendStates) {
+ paths.push(...collectAssetPaths(entry.properties));
+ }
+ }
+ }
+ };
+ for (const layer of getLayers(data)) {
+ scanStates(layer.states);
+ }
+ return paths;
+}
+
function createEntityRuntime(data: StateMachineData): EntityRuntime {
const layers = getLayers(data);
return {
inputs: createInputs(data),
layers: layers.map(l => createLayerRuntime(l.initialState)),
prevHovered: false,
+ assets: new StateMachineAssetCache(gatherAllAssetPaths(data)),
};
}
@@ -156,9 +192,33 @@ function resolveEasing(name?: string): EasingType {
return EASING_MAP[name] ?? EasingType.Linear;
}
+function resolveAssetProperty(
+ ctx: PropertyContext,
+ path: string,
+ value: unknown,
+): boolean {
+ const normalized = normalizeAssetValue(value);
+ if (!normalized) return false;
+ const handle = ctx.assets.getHandle(normalized);
+ if (handle !== undefined) {
+ setEntityProperty(ctx.world, ctx.entity, path, handle);
+ return true;
+ }
+ return false;
+}
+
+function stateHasUnresolvedAssets(state: StateNode, assets: StateMachineAssetCache): boolean {
+ if (!state.properties) return false;
+ for (const [key, value] of Object.entries(state.properties)) {
+ if (!isAssetPropertyPath(key)) continue;
+ const normalized = normalizeAssetValue(value);
+ if (normalized && assets.getHandle(normalized) === undefined) return true;
+ }
+ return false;
+}
+
function applyStateProperties(
- world: World,
- entity: Entity,
+ ctx: PropertyContext,
state: StateNode,
duration: number,
easing: EasingType,
@@ -167,45 +227,53 @@ function applyStateProperties(
if (!state.properties) return;
for (const [path, targetValue] of Object.entries(state.properties)) {
+ if (isAssetPropertyPath(path)) {
+ resolveAssetProperty(ctx, path, targetValue);
+ continue;
+ }
+
if (duration > 0 && typeof targetValue === 'number') {
- const currentValue = getEntityProperty(world, entity, path);
+ const currentValue = getEntityProperty(ctx.world, ctx.entity, path);
if (typeof currentValue !== 'number') {
- setEntityProperty(world, entity, path, targetValue);
+ setEntityProperty(ctx.world, ctx.entity, path, targetValue);
continue;
}
const from = currentValue;
const to = targetValue;
const handle = Tween.value(from, to, duration, (v) => {
- setEntityProperty(world, entity, path, v);
+ setEntityProperty(ctx.world, ctx.entity, path, v);
}, { easing });
runtime.activeTweens.push(handle);
} else {
- setEntityProperty(world, entity, path, targetValue);
+ setEntityProperty(ctx.world, ctx.entity, path, targetValue);
}
}
}
function applyBlendEntryProperties(
- world: World,
- entity: Entity,
+ ctx: PropertyContext,
entry: BlendEntry,
weight: number,
): void {
if (!entry.properties || weight <= 0) return;
for (const [path, targetValue] of Object.entries(entry.properties)) {
+ if (isAssetPropertyPath(path)) {
+ resolveAssetProperty(ctx, path, targetValue);
+ continue;
+ }
+
if (typeof targetValue === 'number') {
- const current = getEntityProperty(world, entity, path);
+ const current = getEntityProperty(ctx.world, ctx.entity, path);
if (typeof current === 'number') {
- setEntityProperty(world, entity, path, current + (targetValue - current) * weight);
+ setEntityProperty(ctx.world, ctx.entity, path, current + (targetValue - current) * weight);
}
}
}
}
function applyBlend1D(
- world: World,
- entity: Entity,
+ ctx: PropertyContext,
state: StateNode,
inputs: Map<string, boolean | number>,
): void {
@@ -215,7 +283,7 @@ function applyBlend1D(
const entries = state.blendStates.slice().sort((a, b) => (a.threshold ?? 0) - (b.threshold ?? 0));
if (entries.length === 1) {
- applyBlendEntryProperties(world, entity, entries[0], 1);
+ applyBlendEntryProperties(ctx, entries[0], 1);
return;
}
@@ -223,11 +291,11 @@ function applyBlend1D(
const maxThreshold = entries[entries.length - 1].threshold ?? 0;
if (inputValue <= minThreshold) {
- applyBlendEntryProperties(world, entity, entries[0], 1);
+ applyBlendEntryProperties(ctx, entries[0], 1);
return;
}
if (inputValue >= maxThreshold) {
- applyBlendEntryProperties(world, entity, entries[entries.length - 1], 1);
+ applyBlendEntryProperties(ctx, entries[entries.length - 1], 1);
return;
}
@@ -237,12 +305,25 @@ function applyBlend1D(
if (inputValue >= lo && inputValue <= hi) {
const range = hi - lo;
const t = range > 0 ? (inputValue - lo) / range : 0;
+ const nearLo = t <= 0.5;
if (entries[i].properties && entries[i + 1].properties) {
for (const [path, loVal] of Object.entries(entries[i].properties!)) {
const hiVal = entries[i + 1].properties![path];
- if (typeof loVal === 'number' && typeof hiVal === 'number') {
+ const isAsset = isAssetPropertyPath(path);
+ if (isAsset) {
+ const loNorm = normalizeAssetValue(loVal);
+ const hiNorm = normalizeAssetValue(hiVal);
+ const loHandle = loNorm ? ctx.assets.getHandle(loNorm) : undefined;
+ const hiHandle = hiNorm ? ctx.assets.getHandle(hiNorm) : undefined;
+ if (loHandle !== undefined || hiHandle !== undefined) {
+ const snapped = nearLo ? loHandle : hiHandle;
+ if (snapped !== undefined) {
+ setEntityProperty(ctx.world, ctx.entity, path, snapped);
+ }
+ }
+ } else if (typeof loVal === 'number' && typeof hiVal === 'number') {
const blended = loVal + (hiVal - loVal) * t;
- setEntityProperty(world, entity, path, blended);
+ setEntityProperty(ctx.world, ctx.entity, path, blended);
}
}
}
@@ -252,8 +333,7 @@ function applyBlend1D(
}
function applyBlendDirect(
- world: World,
- entity: Entity,
+ ctx: PropertyContext,
state: StateNode,
inputs: Map<string, boolean | number>,
): void {
@@ -266,7 +346,7 @@ function applyBlendDirect(
} else {
mix = entry.mixValue ?? 1;
}
- applyBlendEntryProperties(world, entity, entry, mix);
+ applyBlendEntryProperties(ctx, entry, mix);
}
}
@@ -305,17 +385,19 @@ function cleanupTimelineHandle(module: ESEngineModule | null, runtime: LayerRunt
runtime.timelineDuration = 0;
}
-function cleanupEntityRuntime(module: ESEngineModule | null, er: EntityRuntime): void {
+function cleanupEntityRuntime(module: ESEngineModule | null, er: EntityRuntime, assetServer?: AssetServer | null): void {
for (const layer of er.layers) {
cancelActiveTweens(layer);
cleanupTimelineHandle(module, layer);
}
+ if (assetServer) {
+ er.assets.release(assetServer);
+ }
}
function processLayer(
- world: World,
+ ctx: PropertyContext,
module: ESEngineModule,
- entity: Entity,
layerData: LayerData,
layer: LayerRuntime,
inputs: Map<string, boolean | number>,
@@ -323,18 +405,16 @@ function processLayer(
): void {
if (layer.isExited) return;
- // Advance active timeline
if (layer.timelineHandle && layer.timelineUpload && module) {
setTimelineModule(module);
advanceAndProcess(
- world, module,
- layer.timelineHandle, entity,
+ ctx.world, module,
+ layer.timelineHandle, ctx.entity,
dt, 1.0,
layer.timelineUpload,
);
}
- // Evaluate transitions (current state first, then __any__)
const currentState = layerData.states[layer.currentState];
if (!currentState) return;
@@ -375,19 +455,19 @@ function processLayer(
if (stateType === 'blend1d') {
cleanupTimelineHandle(module, layer);
- applyBlend1D(world, entity, targetState, inputs);
+ applyBlend1D(ctx, targetState, inputs);
} else if (stateType === 'blendDirect') {
cleanupTimelineHandle(module, layer);
- applyBlendDirect(world, entity, targetState, inputs);
+ applyBlendDirect(ctx, targetState, inputs);
} else if (targetState.timeline) {
if (module) {
setTimelineModule(module);
- enterTimelineState(world, module, entity, targetState, layer);
+ enterTimelineState(ctx.world, module, ctx.entity, targetState, layer);
}
} else {
cleanupTimelineHandle(module, layer);
applyStateProperties(
- world, entity, targetState,
+ ctx, targetState,
transition.duration,
resolveEasing(transition.easing),
layer,
@@ -395,17 +475,20 @@ function processLayer(
}
layer.currentState = transition.target;
+ layer.pendingAssetApply = stateHasUnresolvedAssets(targetState, ctx.assets);
break;
}
- // Apply blend state properties each frame (not just on transition)
const activeState = layerData.states[layer.currentState];
if (activeState) {
const activeType = activeState.type ?? 'standard';
if (activeType === 'blend1d') {
- applyBlend1D(world, entity, activeState, inputs);
+ applyBlend1D(ctx, activeState, inputs);
} else if (activeType === 'blendDirect') {
- applyBlendDirect(world, entity, activeState, inputs);
+ applyBlendDirect(ctx, activeState, inputs);
+ } else if (layer.pendingAssetApply && !stateHasUnresolvedAssets(activeState, ctx.assets)) {
+ applyStateProperties(ctx, activeState, 0, EasingType.Linear, layer);
+ layer.pendingAssetApply = false;
}
}
}
@@ -415,20 +498,29 @@ export class StateMachinePlugin implements Plugin {
registerComponent('StateMachine', StateMachine);
const world = app.world;
- const runtimes = new Map<Entity, EntityRuntime>();
+ const runtimes = new EntityStateMap<EntityRuntime>();
+ let wasPlayMode = false;
app.addSystemToSchedule(Schedule.Update, defineSystem(
[Res(Time)],
(time: TimeData) => {
const module = world.getWasmModule() as ESEngineModule;
+ const assetServer = app.getResource(Assets);
- for (const entity of runtimes.keys()) {
- if (!world.valid(entity)) {
- const er = runtimes.get(entity)!;
- cleanupEntityRuntime(module, er);
- runtimes.delete(entity);
+ const inPlayMode = !isEditor() || isPlayMode();
+ if (!inPlayMode) {
+ if (wasPlayMode) {
+ for (const [, er] of runtimes) {
+ cleanupEntityRuntime(module, er, assetServer);
+ }
+ runtimes.clear();
}
+ wasPlayMode = false;
+ return;
}
+ wasPlayMode = true;
+
+ runtimes.cleanup(world);
const entities = world.getEntitiesWithComponents([StateMachine]);
@@ -453,7 +545,10 @@ export class StateMachinePlugin implements Plugin {
}
}
- // Listener processing (shared inputs)
+ if (assetServer && er.assets.paths.length > 0 && !er.assets.allLoaded) {
+ er.assets.startLoading(assetServer);
+ }
+
const hasInteraction = world.has(entity, UIInteraction);
if (hasInteraction) {
const interaction = world.get(entity, UIInteraction) as UIInteractionData;
@@ -475,14 +570,13 @@ export class StateMachinePlugin implements Plugin {
}
}
- // Process each layer sequentially (last-write-wins for properties)
+ const ctx: PropertyContext = { world, entity, assets: er.assets };
for (let i = 0; i < layerDefs.length; i++) {
if (i < er.layers.length) {
- processLayer(world, module, entity, layerDefs[i], er.layers[i], er.inputs, time.delta);
+ processLayer(ctx, module, layerDefs[i], er.layers[i], er.inputs, time.delta);
}
}
- // Clear trigger inputs
for (const inputDef of data.inputs) {
if (inputDef.type === 'trigger') {
er.inputs.set(inputDef.name, false);
diff --git a/sdk/src/ui/index.ts b/sdk/src/ui/index.ts
index eb977f88a..db5fbe405 100644
--- a/sdk/src/ui/index.ts
+++ b/sdk/src/ui/index.ts
@@ -389,6 +389,7 @@ export {
evaluateCondition,
} from './StateMachinePlugin';
+
// Property Path Utilities
export {
getNestedProperty,