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.

fix(editor): a sprite handed a texture takes that texture's size

yhh02f4e89495e5
diff --git a/desktop/scripts/editor-checks/sprite-texture-fit.mjs b/desktop/scripts/editor-checks/sprite-texture-fit.mjs
new file mode 100644
index 000000000..a500790e4
--- /dev/null
+++ b/desktop/scripts/editor-checks/sprite-texture-fit.mjs
@@ -0,0 +1,104 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file sprite-texture-fit — a sprite handed a texture is the size of that texture.
+ *
+ * `Sprite.size` starts at the 100×100 placeholder that makes a textureless sprite
+ * visible. A sprite handed an image must leave that behind, or it draws its art
+ * stretched to a size nobody chose with nothing on screen saying why.
+ *
+ * The fit is a rule about a size nobody chose, so the cases that matter are the two
+ * sides of "nobody chose it": it must follow the texture while the size is still
+ * this rule's, and it must never touch a size the creator typed.
+ */
+import path from 'node:path';
+import { cp, mkdir } from 'node:fs/promises';
+import { makeProject, checker, DESKTOP } from '../lib/editorDriver.mjs';
+
+// Real project images, so the expected numbers are the files' own headers rather
+// than a fixture's promise: star is 31×30, arrow 32×32. Deliberately different, and
+// deliberately not square — a swapped axis has nowhere to hide.
+const EXAMPLE = path.resolve(DESKTOP, '..', 'examples', 'sprite-rendering');
+const STAR = [31, 30];
+const ARROW = [32, 32];
+
+const PROJECT = JSON.stringify({
+ formatVersion: '1', name: 'Sprite Fit Check', version: '0.1.0',
+ defaultScene: 'assets/scenes/main.esscene',
+ designResolution: { width: 800, height: 600 },
+}, null, 2);
+
+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 } },
+ ],
+ }],
+}, null, 1);
+
+export const name = 'sprite-texture-fit';
+export const describes = 'assigning a texture sizes the sprite to it, and never overwrites a size the creator set';
+
+export async function run(ed) {
+ const root = await makeProject({ 'project.esproject': PROJECT, 'assets/scenes/main.esscene': SCENE });
+ await mkdir(path.join(root, 'assets/textures'), { recursive: true });
+ for (const f of ['star.png', 'star.png.meta', 'arrow.png', 'arrow.png.meta']) {
+ await cp(path.join(EXAMPLE, 'assets/textures', f), path.join(root, 'assets/textures', f));
+ }
+ const check = checker();
+
+ await ed.open(root, 'assets/scenes/main.esscene');
+ await ed.sleep(800);
+
+ const created = await ed.json('create_entity', { template: 'anchor:Sprite', name: 'S1' }, 30000);
+ const id = typeof created === 'number' ? created : created?.id;
+ if (!check(id != null, `create_entity did not return an id (${JSON.stringify(created)})`)) return check.failures;
+
+ const size = () => ed.json('get_field_value', { entity: id, component: 'Sprite', key: 'size' }, 20000);
+ const setTexture = (file) =>
+ ed.call('set_field', { entity: id, component: 'Sprite', key: 'texture', type: 'asset', value: `assets/textures/${file}` }, 30000);
+ // The fit is deferred past the write it reacts to, and decodes the image the first
+ // time it sees one — so settle before reading rather than racing it.
+ const settle = () => ed.sleep(1200);
+
+ check(
+ JSON.stringify(await size()) === '[100,100]',
+ 'a fresh Sprite does not start at the 100×100 placeholder — this check no longer measures what it thinks',
+ );
+
+ await setTexture('star.png');
+ await settle();
+ const fitted = await size();
+ check(
+ JSON.stringify(fitted) === JSON.stringify(STAR),
+ `assigning a ${STAR[0]}×${STAR[1]} texture left the sprite at ${JSON.stringify(fitted)} — the art draws `
+ + 'stretched to a size nobody chose, which is only invisible because the placeholder is square-ish',
+ );
+
+ // A size that came from the previous texture is still nobody's choice, so a swap
+ // re-fits; otherwise the first texture a sprite ever gets would pin its size forever.
+ await setTexture('arrow.png');
+ await settle();
+ const swapped = await size();
+ check(
+ JSON.stringify(swapped) === JSON.stringify(ARROW),
+ `swapping to a ${ARROW[0]}×${ARROW[1]} texture left the sprite at ${JSON.stringify(swapped)} — an auto-fitted `
+ + 'size did not follow the texture it was fitted to',
+ );
+
+ // The other half of the rule, and the one that would be a data-loss bug: an
+ // authored size is the creator's, and a texture change must not touch it.
+ await ed.call('set_field', { entity: id, component: 'Sprite', key: 'size', type: 'vec2', value: [7, 9] }, 20000);
+ await setTexture('star.png');
+ await settle();
+ const kept = await size();
+ check(
+ JSON.stringify(kept) === '[7,9]',
+ `a hand-set size of [7,9] became ${JSON.stringify(kept)} when the texture changed — the auto-fit is `
+ + 'overwriting authored values, which loses work silently',
+ );
+ return check.failures;
+}
diff --git a/desktop/src/main.tsx b/desktop/src/main.tsx
index fba9858b4..be484a6c5 100644
--- a/desktop/src/main.tsx
+++ b/desktop/src/main.tsx
@@ -53,6 +53,7 @@ import { EngineHost } from './engine/EngineHost';
import { Particle, getComponent, takeCensus } from 'esengine';
import { actionNames, actionParams, conditionNames } from '@/ai/actionCatalog';
import { applyFxPreview, initFxPreviewEditRestart } from './engine/fxPreview';
+import { initSpriteAutoFit } from './project/spriteAutoFit';
import { commands } from './commands/registry';
import { captureBuildStamp, captureAppVersion, collectBundle } from './diagnostics';
import { allEntitySources, sourceById, createFromSource, type TileGridConfig } from './engine/entitySources';
@@ -111,6 +112,7 @@ initPlugins();
// wire the Details-edit → emitter-restart glue.
applyFxPreview(useEditorStore.getState().previewFx);
initFxPreviewEditRestart();
+initSpriteAutoFit();
/** The open document: a scene, or the prefab being edited in Prefab Mode. `dirty` is
* the aggregate registry (scene + every open asset editor), the same truth the
diff --git a/desktop/src/project/ProjectStore.ts b/desktop/src/project/ProjectStore.ts
index 84e9afad6..9f2b2b2f7 100644
--- a/desktop/src/project/ProjectStore.ts
+++ b/desktop/src/project/ProjectStore.ts
@@ -4,6 +4,7 @@ import { createStore } from 'zustand/vanilla';
import { getComponent, Assets, migratePrefabData, extractPrefab, flattenPrefab, collectExternalEntityRefs, collapseInstance, applyDeltaToSource, buildVariant, textureImportSettingsFrom, Renderer, RETIRED_COMPONENT_TYPES, parseThemeOverrides, resolveAssetGroup, folderGroupMode, withFolderGroup, folderAlwaysInclude, withFolderAlwaysInclude, withActiveRemoteRoot, Audio, applyAudioProjectConfig } from 'esengine';
import { importerDefaults, applyImporterEdit } from './assetImporter';
import { AssetRegistry, UUID_PREFIX, refUuid, type AssetEntryLite } from './AssetRegistry';
+import { imageSize } from './imageSize';
import { PrefabCache } from './PrefabCache';
import {
runtimeConfigOf, packagedRuntimeFields, normalizeCollisionLayers, normalizeCollisionLayerMasks,
@@ -1321,24 +1322,13 @@ class ProjectStoreImpl {
async instantiateSpriteFromPath(path: string, position: { x: number; y: number }): Promise<number | null> {
const ref = await AssetRegistry.assetRefForPath(path, 'texture');
if (!ref) return null;
- const size = await this.imageNaturalSize(path);
+ const size = await imageSize(path);
const name = (path.split('/').pop() ?? 'Sprite').replace(/\.[^.]+$/, '') || 'Sprite';
const id = SceneCommands.create(spritePrefab(name, ref, size), { parent: null, position });
if (id != null) useSelection.getState().select(id);
return id;
}
- /** Natural pixel size of a project image via the `estella://` transport; a sane
- * fallback if it can't decode (so a dropped sprite is never zero-sized). */
- private imageNaturalSize(path: string): Promise<{ x: number; y: number }> {
- return new Promise((resolve) => {
- const img = new Image();
- img.onload = () => resolve({ x: img.naturalWidth || 100, y: img.naturalHeight || 100 });
- img.onerror = () => resolve({ x: 100, y: 100 });
- img.src = `estella://project/${path}`;
- });
- }
-
/**
* Create a `.esprefab` asset from a live entity subtree (the "Create Prefab"
* authoring path — the inverse of {@link instantiatePrefabFromPath}). Extracts
diff --git a/desktop/src/project/imageSize.ts b/desktop/src/project/imageSize.ts
new file mode 100644
index 000000000..54e16c086
--- /dev/null
+++ b/desktop/src/project/imageSize.ts
@@ -0,0 +1,63 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file imageSize.ts — a project image's pixel dimensions, decoded once.
+ *
+ * Several places need "how big is this PNG" for real geometry, not decoration: the
+ * size a dropped sprite spawns at, the size an assigned texture fits to, a tileset's
+ * grid. Each decoding its own `new Image()` means one project image is decoded once
+ * per asker, and — worse — an asker that needs the answer NOW has to go async even
+ * though something else already has it. One cache, so the second asker is free.
+ */
+
+/** A decoded image's pixel dimensions. */
+export interface ImageSize {
+ x: number;
+ y: number;
+}
+
+const cache = new Map<string, ImageSize>();
+const inFlight = new Map<string, Promise<ImageSize>>();
+
+/** The fallback for an image that cannot be decoded — never zero, so a sprite built
+ * from it is still visible and selectable rather than a zero-area quad. */
+export const FALLBACK_IMAGE_SIZE: ImageSize = { x: 100, y: 100 };
+
+/** The dimensions if they are already known, else null — the synchronous read, for a
+ * caller that can only act inside the current tick (an undo-coalescing edit). */
+export function peekImageSize(path: string): ImageSize | null {
+ return cache.get(path) ?? null;
+}
+
+/** The dimensions of a project image, decoded through the `estella://` transport and
+ * memoized by path. Concurrent asks for one path share a single decode. */
+export function imageSize(path: string): Promise<ImageSize> {
+ const hit = cache.get(path);
+ if (hit) return Promise.resolve(hit);
+ const running = inFlight.get(path);
+ if (running) return running;
+ const p = new Promise<ImageSize>((resolve) => {
+ const img = new Image();
+ const done = (size: ImageSize) => {
+ cache.set(path, size);
+ inFlight.delete(path);
+ resolve(size);
+ };
+ img.onload = () => done(
+ img.naturalWidth > 0 && img.naturalHeight > 0
+ ? { x: img.naturalWidth, y: img.naturalHeight }
+ : FALLBACK_IMAGE_SIZE,
+ );
+ img.onerror = () => done(FALLBACK_IMAGE_SIZE);
+ img.src = `estella://project/${path}`;
+ });
+ inFlight.set(path, p);
+ return p;
+}
+
+/** Drop a path's cached size — the image on disk changed (re-import, external edit),
+ * so the next ask must decode again. */
+export function invalidateImageSize(path: string): void {
+ cache.delete(path);
+ inFlight.delete(path);
+}
diff --git a/desktop/src/project/spriteAutoFit.ts b/desktop/src/project/spriteAutoFit.ts
new file mode 100644
index 000000000..aa82c6c4c
--- /dev/null
+++ b/desktop/src/project/spriteAutoFit.ts
@@ -0,0 +1,85 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file spriteAutoFit.ts — a sprite handed a texture takes that texture's size.
+ *
+ * `Sprite.size` is world units, deliberately independent of the image, and its
+ * authoring default is 100×100 so a textureless sprite is a visible placeholder.
+ * That default then outlived its purpose: assigning a 64×48 image left the quad at
+ * 100×100 with the art stretched, and nothing on screen said why. Only dragging an
+ * image into the viewport was right, because that path alone knew the pixel size.
+ *
+ * So the size follows the texture at the ONE place a texture is assigned — an edit
+ * hook, rather than every caller remembering — and only while the size is still one
+ * this rule chose: the untouched default, or the fit to the texture being replaced.
+ * An authored size is never overwritten.
+ */
+import { SceneCommands } from '@/engine/SceneCommands';
+import { SceneQuery } from '@/engine/SceneQuery';
+import { defaultDataFor } from '@/engine/schema';
+import { AssetRegistry } from '@/project/AssetRegistry';
+import { imageSize, peekImageSize, type ImageSize } from '@/project/imageSize';
+
+type Vec2 = [number, number];
+
+const vecEq = (a: Vec2 | null, b: Vec2 | null): boolean =>
+ !!a && !!b && Math.abs(a[0] - b[0]) < 0.001 && Math.abs(a[1] - b[1]) < 0.001;
+
+const vecOf = (v: unknown): Vec2 | null => (Array.isArray(v) && v.length >= 2 ? [Number(v[0]), Number(v[1])] : null);
+
+const field = (sourceId: number, key: string): unknown => SceneQuery.getFieldValue(sourceId, 'Sprite', key);
+
+/** The image path behind a texture ref (`@uuid:` or a project-relative path), or null. */
+const texturePath = (ref: unknown): string | null => AssetRegistry.assetInfo(ref)?.path ?? null;
+
+/**
+ * The size a sprite takes from a texture. The drawn region is the texture's pixels
+ * through `uvScale`, so a sprite already showing an atlas sub-rect fits that frame
+ * rather than the whole sheet.
+ */
+function fitSize(sourceId: number, natural: ImageSize): Vec2 {
+ const uv = vecOf(field(sourceId, 'uvScale')) ?? [1, 1];
+ return [Math.round(natural.x * Math.abs(uv[0])), Math.round(natural.y * Math.abs(uv[1]))];
+}
+
+/** Whether the current size is one this rule owns: the authoring default, or the fit
+ * to the texture being replaced. Anything else is the creator's number. */
+function mayRefit(sourceId: number, previousRef: unknown): boolean {
+ const size = vecOf(field(sourceId, 'size'));
+ if (!size) return false;
+ const dflt = defaultDataFor('Sprite').size as { x: number; y: number } | undefined;
+ if (dflt && vecEq(size, [dflt.x, dflt.y])) return true;
+ const prev = texturePath(previousRef);
+ const prevNatural = prev ? peekImageSize(prev) : null;
+ return !!prevNatural && vecEq(size, fitSize(sourceId, prevNatural));
+}
+
+/** Its own undo step, named for what it did. The fit necessarily lands after the
+ * texture write it reacts to, so it cannot join that step — which leaves undo saying
+ * "Fit Sprite To Texture" once and "Edit Texture" again, and lets a creator who wants
+ * the texture at the size they had keep it by undoing only the fit. */
+function refit(sourceId: number, natural: ImageSize): void {
+ const size = fitSize(sourceId, natural);
+ if (vecEq(vecOf(field(sourceId, 'size')), size)) return;
+ SceneCommands.transact('Fit Sprite To Texture', () => {
+ SceneCommands.setField(sourceId, 'Sprite', 'size', 'vec2', size);
+ });
+}
+
+/** Wire the texture-assigned → size-follows glue (call once at editor boot). */
+export function initSpriteAutoFit(): void {
+ SceneCommands.addEditHook((sourceId, compName, key, _type, value) => {
+ if (compName !== 'Sprite' || key !== 'texture') return false;
+ const path = texturePath(value);
+ // Both questions are asked BEFORE the write lands: afterwards there is no
+ // previous texture left to ask whether the size was fitted to it.
+ if (path && mayRefit(sourceId, field(sourceId, 'texture'))) {
+ // The hook runs BEFORE the write, so the fit is deferred past it — otherwise
+ // `uvScale` and the texture it reads would still describe the old assignment.
+ const known = peekImageSize(path);
+ if (known) queueMicrotask(() => refit(sourceId, known));
+ else void imageSize(path).then((natural) => refit(sourceId, natural));
+ }
+ return false; // observe-only
+ });
+}