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.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
feat(tilemap): UE stamp brush + flipD render + terrain autotile
esengineae3255c222c1
diff --git a/desktop/package.json b/desktop/package.jsonindex 2c6178b30..3ce84838b 100644--- a/desktop/package.json+++ b/desktop/package.json@@ -23,6 +23,7 @@"verify:render:text:rect": "vite build && ESTELLA_VERIFY_SCENE=/scenes/ui-text-rect.esscene ESTELLA_VERIFY_MANIFEST=/scenes/ui-text-sdf.textures.json electron scripts/headless-verify.mjs","verify:render:uinode": "vite build && ESTELLA_VERIFY_SCENE=/scenes/ui-node-flex.esscene ESTELLA_VERIFY_MANIFEST=/scenes/ui-node-flex.textures.json ESTELLA_VERIFY_W=800 ESTELLA_VERIFY_H=600 electron scripts/headless-verify.mjs","verify:render:tilemap": "vite build && ESTELLA_VERIFY_SCENE=/scenes/tilemap-flip.esscene ESTELLA_VERIFY_MANIFEST=/scenes/tilemap-flip.textures.json ESTELLA_VERIFY_W=256 ESTELLA_VERIFY_H=256 ESTELLA_VERIFY_STEPS=2 ESTELLA_VERIFY_EXPECT=\"[{\\\"x\\\":0.46,\\\"y\\\":0.5,\\\"rgb\\\":[255,0,0]},{\\\"x\\\":0.84,\\\"y\\\":0.5,\\\"rgb\\\":[0,255,0]},{\\\"x\\\":0.46,\\\"y\\\":0.84,\\\"rgb\\\":[0,0,255]},{\\\"x\\\":0.84,\\\"y\\\":0.84,\\\"rgb\\\":[255,255,0]}]\" electron scripts/headless-verify.mjs",+ "verify:render:tilemap:transform": "vite build && ESTELLA_VERIFY_SCENE=/scenes/tilemap-transform.esscene ESTELLA_VERIFY_MANIFEST=/scenes/tilemap-transform.textures.json ESTELLA_VERIFY_W=256 ESTELLA_VERIFY_H=256 ESTELLA_VERIFY_STEPS=2 ESTELLA_VERIFY_EXPECT=\"[{\\\"x\\\":0.40,\\\"y\\\":0.36,\\\"rgb\\\":[255,255,0]},{\\\"x\\\":0.60,\\\"y\\\":0.36,\\\"rgb\\\":[0,255,0]},{\\\"x\\\":0.40,\\\"y\\\":0.58,\\\"rgb\\\":[0,0,255]},{\\\"x\\\":0.60,\\\"y\\\":0.58,\\\"rgb\\\":[255,0,0]}]\" electron scripts/headless-verify.mjs","verify:render:material": "vite build && ESTELLA_VERIFY_SCENE=/scenes/mat-tint.esscene ESTELLA_VERIFY_MANIFEST=/scenes/mat-tint.textures.json ESTELLA_VERIFY_W=256 ESTELLA_VERIFY_H=256 ESTELLA_VERIFY_STEPS=2 ESTELLA_VERIFY_EXPECT=\"[{\\\"x\\\":0.5,\\\"y\\\":0.5,\\\"rgb\\\":[255,0,0],\\\"tol\\\":40}]\" electron scripts/headless-verify.mjs","verify:render:material:instance": "vite build && ESTELLA_VERIFY_SCENE=/scenes/mat-instance.esscene ESTELLA_VERIFY_MANIFEST=/scenes/mat-instance.textures.json ESTELLA_VERIFY_W=256 ESTELLA_VERIFY_H=256 ESTELLA_VERIFY_STEPS=2 ESTELLA_VERIFY_EXPECT=\"[{\\\"x\\\":0.5,\\\"y\\\":0.5,\\\"rgb\\\":[0,255,0],\\\"tol\\\":40}]\" electron scripts/headless-verify.mjs","verify:render:material:texture": "vite build && ESTELLA_VERIFY_SCENE=/scenes/mat-tex.esscene ESTELLA_VERIFY_MANIFEST=/scenes/mat-tex.textures.json ESTELLA_VERIFY_W=256 ESTELLA_VERIFY_H=256 ESTELLA_VERIFY_STEPS=2 ESTELLA_VERIFY_EXPECT=\"[{\\\"x\\\":0.5,\\\"y\\\":0.5,\\\"rgb\\\":[0,255,0],\\\"tol\\\":50}]\" electron scripts/headless-verify.mjs",diff --git a/desktop/public/scenes/tilemap-transform.esscene b/desktop/public/scenes/tilemap-transform.esscenenew file mode 100644index 000000000..58e037f7d--- /dev/null+++ b/desktop/public/scenes/tilemap-transform.esscene@@ -0,0 +1,67 @@+{+ "version": "1.0",+ "name": "TilemapTransform",+ "entities": [+ {+ "id": 0,+ "name": "Camera",+ "parent": null,+ "children": [],+ "components": [+ {+ "type": "Transform",+ "data": {+ "position": {+ "x": 16,+ "y": -16,+ "z": 10+ }+ }+ },+ {+ "type": "Camera",+ "data": {+ "projectionType": 1,+ "orthoSize": 40,+ "isActive": true,+ "priority": 0+ }+ }+ ],+ "visible": true+ },+ {+ "id": 1,+ "name": "Tilemap",+ "parent": null,+ "children": [],+ "components": [+ {+ "type": "Transform",+ "data": {+ "position": {+ "x": 0,+ "y": 0,+ "z": 0+ }+ }+ },+ {+ "type": "TilemapLayer",+ "data": {+ "cellSize": {+ "x": 32,+ "y": 32+ },+ "tileset": "@uuid:aaaaaaaa-1111-2222-3333-444444444444",+ "tilesetColumns": 1,+ "tilesetRows": 1,+ "visible": true,+ "chunks": "RVNUTQEAAAAAAAAAAAAAAAGAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"+ }+ }+ ],+ "visible": true+ }+ ]+}diff --git a/desktop/public/scenes/tilemap-transform.textures.json b/desktop/public/scenes/tilemap-transform.textures.jsonnew file mode 100644index 000000000..fb0dcfaf6--- /dev/null+++ b/desktop/public/scenes/tilemap-transform.textures.json@@ -0,0 +1,3 @@+{+ "aaaaaaaa-1111-2222-3333-444444444444": "/scenes/tilemap-flip/atlas.png"+}diff --git a/desktop/src/panels/TilemapPainter.tsx b/desktop/src/panels/TilemapPainter.tsxindex 1dff98f95..bbdde14b9 100644--- a/desktop/src/panels/TilemapPainter.tsx+++ b/desktop/src/panels/TilemapPainter.tsx@@ -2,15 +2,16 @@// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team/*** @file TilemapPainter.tsx- * @brief The Tilemap painter panel — the brush palette + tools- * for painting a selected scene `TilemapLayer` entity. Painting itself happens- * in the Viewport (this panel drives the active tool + brush via the paint- * store); the palette is the entity's referenced `.estileset` atlas.+ * @brief The Tilemap painter panel — the brush palette + tools for painting a selected+ * scene `TilemapLayer`. The palette is the entity's referenced `.estileset`+ * atlas; drag a rectangle over it to pick a multi-tile stamp, single-click for a+ * 1×1 brush. Flip/rotate transform the active stamp. Painting itself happens in+ * the Viewport (this panel drives the active tool + stamp via the paint store).*/-import { useEffect, useState } from 'react';-import { Brush, Eraser, Square, Pipette } from 'lucide-react';-import { parseTileset, type TilesetAsset } from 'esengine';+import { useEffect, useRef, useState } from 'react';+import { Brush, Eraser, Square, Pipette, FlipHorizontal, FlipVertical, RotateCw, Mountain } from 'lucide-react';+import { parseTileset, encodeTile, type TilesetAsset } from 'esengine';import { useTilemapPaint, type PaintTool } from '@/store/tilemapPaintStore';import { useSelection } from '@/store/selectionStore';import { SceneModel } from '@/engine/SceneModel';@@ -30,8 +31,11 @@ const TOOLS: { id: PaintTool; icon: typeof Brush; label: string }[] = [{ id: 'erase', icon: Eraser, label: '擦除' },{ id: 'rect', icon: Square, label: '矩形' },{ id: 'eyedropper', icon: Pipette, label: '吸管' },+ { id: 'terrain', icon: Mountain, label: '地形' },];+const TERRAIN_COLORS = ['#4caf50', '#d6884c', '#4c8fd6', '#b14cd6', '#d6c64c', '#d64c6e'];+/** Resolve the .estileset path a selected TilemapLayer references (its `tilesetAsset` @uuid). */function selectedTilemapTilesetPath(selectedId: number | null): string | null {if (selectedId == null) return null;@@ -42,8 +46,16 @@ function selectedTilemapTilesetPath(selectedId: number | null): string | null {return typeof ref === 'string' ? (ProjectStore.assetInfo(ref)?.path ?? null) : null;}+interface SelRect { c0: number; r0: number; c1: number; r1: number }+const normRect = (a: { c: number; r: number }, b: { c: number; r: number }): SelRect => ({+ c0: Math.min(a.c, b.c), r0: Math.min(a.r, b.r), c1: Math.max(a.c, b.c), r1: Math.max(a.r, b.r),+});+export function TilemapPainter() {- const { tilesetPath, brushTileId, tool, setTileset, setBrush, setTool } = useTilemapPaint();+ const {+ tilesetPath, stamp, tool, terrainSet,+ setTileset, setTilesetAsset, setStamp, setTool, setTerrainSet, flipH, flipV, rotateCW,+ } = useTilemapPaint();const selectedId = useSelection((s) => s.selectedId);const hasTilemap = selectedId != null&& !!SceneModel.entityBySource(selectedId)?.components.some((c) => c.type === 'TilemapLayer');@@ -57,20 +69,41 @@ export function TilemapPainter() {const [asset, setAsset] = useState<TilesetAsset | null>(null);useEffect(() => {let alive = true;- if (!tilesetPath) { setAsset(null); return; }+ if (!tilesetPath) { setAsset(null); setTilesetAsset(null); return; }void (async () => {try {const a = parseTileset(JSON.parse(await window.estella.fs.read(tilesetPath)));- if (alive) setAsset(a);- } catch { if (alive) setAsset(null); }+ if (alive) { setAsset(a); setTilesetAsset(a); }+ } catch { if (alive) { setAsset(null); setTilesetAsset(null); } }})();return () => { alive = false; };- }, [tilesetPath]);+ }, [tilesetPath, setTilesetAsset]);const texUrl = asset ? `estella://project/${ProjectStore.assetInfo(asset.texture)?.path ?? ''}` : null;const [natural, setNatural] = useState<{ w: number; h: number } | null>(null);useEffect(() => setNatural(null), [texUrl]);+ // Palette marquee: drag a rectangle of cells to pick a multi-tile stamp.+ const [sel, setSel] = useState<SelRect | null>(null);+ const dragAnchor = useRef<{ c: number; r: number } | null>(null);++ // H/V/R transform the active stamp — only while a paint tool is active, so they don't+ // shadow the transform-tool shortcuts when not painting.+ useEffect(() => {+ const onKey = (e: KeyboardEvent) => {+ const st = useTilemapPaint.getState();+ if (!st.tool || e.metaKey || e.ctrlKey || e.altKey) return;+ const t = e.target as HTMLElement | null;+ if (t && (t.tagName === 'INPUT' || t.tagName === 'TEXTAREA' || t.isContentEditable)) return;+ const k = e.key.toLowerCase();+ if (k === 'h') { st.flipH(); e.preventDefault(); }+ else if (k === 'v') { st.flipV(); e.preventDefault(); }+ else if (k === 'r') { st.rotateCW(); e.preventDefault(); }+ };+ window.addEventListener('keydown', onKey);+ return () => window.removeEventListener('keydown', onKey);+ }, []);+if (!hasTilemap) {return (<div className="tp-empty">@@ -87,6 +120,27 @@ export function TilemapPainter() {const cols = natural ? colsFor(natural.w, tw, mg, sp) : (asset?.columns ?? 1);const rows = natural ? rowsFor(natural.h, th, mg, sp) : 0;+ const commitSel = (r: SelRect) => {+ const w = r.c1 - r.c0 + 1;+ const h = r.r1 - r.r0 + 1;+ const cells: number[] = [];+ for (let dy = 0; dy < h; dy++) {+ for (let dx = 0; dx < w; dx++) {+ cells.push(encodeTile((r.r0 + dy) * cols + (r.c0 + dx) + 1));+ }+ }+ setStamp({ w, h, cells });+ if (!tool || tool === 'eyedropper') setTool('brush');+ };++ const endDrag = () => {+ if (dragAnchor.current && sel) commitSel(sel);+ dragAnchor.current = null;+ };++ const inSel = (col: number, row: number): boolean =>+ sel != null && col >= sel.c0 && col <= sel.c1 && row >= sel.r0 && row <= sel.r1;+const cells = [];if (texUrl && natural) {for (let row = 0; row < rows; row++) {@@ -95,10 +149,17 @@ export function TilemapPainter() {cells.push(<divkey={id}- className={'tp-cell' + (id === brushTileId ? ' is-sel' : '')}+ className={'tp-cell' + (inSel(col, row) ? ' is-sel' : '')}style={{ left: mg + col * (tw + sp), top: mg + row * (th + sp), width: tw, height: th }}title={`#${id}`}- onPointerDown={() => { setBrush(id); if (!tool || tool === 'eyedropper') setTool('brush'); }}+ onPointerDown={(e) => {+ e.preventDefault();+ dragAnchor.current = { c: col, r: row };+ setSel({ c0: col, r0: row, c1: col, r1: row });+ }}+ onPointerEnter={() => {+ if (dragAnchor.current) setSel(normRect(dragAnchor.current, { c: col, r: row }));+ }}/>,);}@@ -119,22 +180,52 @@ export function TilemapPainter() {<t.icon size={15} /></button>))}+ <span className="tp-sep" />+ <button type="button" className="tp-tool" title="水平翻转 (H)" onClick={() => flipH()}>+ <FlipHorizontal size={15} />+ </button>+ <button type="button" className="tp-tool" title="垂直翻转 (V)" onClick={() => flipV()}>+ <FlipVertical size={15} />+ </button>+ <button type="button" className="tp-tool" title="旋转 90° (R)" onClick={() => rotateCW()}>+ <RotateCw size={15} />+ </button><span className="tp-grow" />- <span className="tp-brush">刷子 #{brushTileId}</span>- </div>- <div className="tp-palette">- {!texUrl ? (- <div className="tp-warn">没有调色板(瓦片地图未引用 .estileset)</div>- ) : (- <div className="tp-atlas" style={{ width: natural?.w ?? 0, height: natural?.h ?? 0 }}>- <img- className="tp-img" src={texUrl} alt="" draggable={false}- onLoad={(e) => setNatural({ w: e.currentTarget.naturalWidth, h: e.currentTarget.naturalHeight })}- />- {cells}- </div>- )}+ <span className="tp-brush">{tool === 'terrain' ? '地形画笔' : `刷子 ${stamp.w}×${stamp.h}`}</span></div>+ {tool === 'terrain' ? (+ <div className="tp-terrains">+ {(asset?.terrains ?? []).length === 0 ? (+ <div className="tp-warn">没有地形(在瓦片集编辑器的「地形」模式里新建并标记瓦片)</div>+ ) : (+ (asset?.terrains ?? []).map((t, i) => (+ <button+ key={i}+ type="button"+ className={'tp-terrain' + (i === terrainSet ? ' is-active' : '')}+ onClick={() => setTerrainSet(i)}+ >+ <span className="tp-tswatch" style={{ background: TERRAIN_COLORS[i % TERRAIN_COLORS.length] }} />+ {t.name}+ </button>+ ))+ )}+ </div>+ ) : (+ <div className="tp-palette" onPointerUp={endDrag} onPointerLeave={endDrag}>+ {!texUrl ? (+ <div className="tp-warn">没有调色板(瓦片地图未引用 .estileset)</div>+ ) : (+ <div className="tp-atlas" style={{ width: natural?.w ?? 0, height: natural?.h ?? 0 }}>+ <img+ className="tp-img" src={texUrl} alt="" draggable={false}+ onLoad={(e) => setNatural({ w: e.currentTarget.naturalWidth, h: e.currentTarget.naturalHeight })}+ />+ {cells}+ </div>+ )}+ </div>+ )}</div>);}diff --git a/desktop/src/panels/TilesetEditor.tsx b/desktop/src/panels/TilesetEditor.tsxindex 830b3bdd0..b3208c33b 100644--- a/desktop/src/panels/TilesetEditor.tsx+++ b/desktop/src/panels/TilesetEditor.tsx@@ -2,18 +2,23 @@// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team/*** @file TilesetEditor.tsx- * @brief The .estileset editor panel — the tileset's- * atlas with a grid overlay; click/drag tiles to toggle box collision (the- * collision authority every tilemap derives from). Subscribes to the reactive- * TilesetDocument; mutations go through TilesetCommands (one undo step each).+ * @brief The .estileset editor panel — the tileset's atlas with a grid overlay, in two+ * authoring modes. Collision: click/drag tiles to toggle box collision. Terrain:+ * manage autotile sets and click a tile's peering zones (sides + corners) to+ * mark which neighbours it expects, the data the painter's terrain brush resolves+ * against. Subscribes to the reactive TilesetDocument; mutations go through+ * TilesetCommands (one undo step each).*- * Scope: grid geometry + per-tile box collision. Per-tile polygon shapes, animation and- * terrain rules slot onto the same asset later (the schema already carries them).+ * Scope: grid geometry + box collision + terrain peering. Per-tile polygon shapes and+ * animation slot onto the same asset later (the schema already carries them).*/-import { useEffect, useRef, useState, useSyncExternalStore } from 'react';-import { Save } from 'lucide-react';-import type { TilesetAsset } from 'esengine';+import { useEffect, useRef, useState, useSyncExternalStore, type CSSProperties } from 'react';+import { Save, Plus, Trash2 } from 'lucide-react';+import {+ TB_N, TB_E, TB_S, TB_W, TB_NE, TB_SE, TB_SW, TB_NW,+ type TilesetAsset, type TerrainMode,+} from 'esengine';import { TilesetDocument } from '@/tileset/TilesetDocument';import { TilesetCommands } from '@/tileset/TilesetCommands';import { ProjectStore } from '@/project/ProjectStore';@@ -27,6 +32,8 @@ function rowsFor(height: number, tileH: number, margin: number, spacing: number)return stride > 0 ? Math.max(0, Math.floor((height - margin + spacing) / stride)) : 0;}+const TERRAIN_COLORS = ['#4caf50', '#d6884c', '#4c8fd6', '#b14cd6', '#d6c64c', '#d64c6e'];+/** A grid-geometry number field that commits on blur/Enter (one undo step per edit). */function GridField(props: { label: string; value: number; min?: number; onCommit: (n: number) => void }) {const [text, setText] = useState(String(props.value));@@ -49,6 +56,18 @@ function GridField(props: { label: string; value: number; min?: number; onCommit);}+// Peering zones in the cell's 3×3 grid; center (membership) is handled separately.+const ZONES: { gx: number; gy: number; bit: number; corner: boolean }[] = [+ { gx: 1, gy: 0, bit: TB_N, corner: false },+ { gx: 2, gy: 0, bit: TB_NE, corner: true },+ { gx: 2, gy: 1, bit: TB_E, corner: false },+ { gx: 2, gy: 2, bit: TB_SE, corner: true },+ { gx: 1, gy: 2, bit: TB_S, corner: false },+ { gx: 0, gy: 2, bit: TB_SW, corner: true },+ { gx: 0, gy: 1, bit: TB_W, corner: false },+ { gx: 0, gy: 0, bit: TB_NW, corner: true },+];+export function TilesetEditor() {useSyncExternalStore(TilesetDocument.subscribe, TilesetDocument.getRevision);const asset = TilesetDocument.asset;@@ -59,7 +78,10 @@ export function TilesetEditor() {const [natural, setNatural] = useState<{ w: number; h: number } | null>(null);const [zoom, setZoom] = useState(2);- // Live paint stroke: which tiles + the target on/off state, committed as one undo step.+ const [mode, setMode] = useState<'collision' | 'terrain'>('collision');+ const [activeSet, setActiveSet] = useState(0);+ const [hovered, setHovered] = useState<number | null>(null);+ // Live collision paint stroke: which tiles + the target on/off state, one undo step.const [drag, setDrag] = useState<{ ids: Set<number>; on: boolean } | null>(null);const dragRef = useRef(drag);dragRef.current = drag;@@ -78,6 +100,9 @@ export function TilesetEditor() {const { tileWidth: tw, tileHeight: th, margin: mg, spacing: sp } = asset;const cols = natural ? colsFor(natural.w, tw, mg, sp) : asset.columns;const rows = natural ? rowsFor(natural.h, th, mg, sp) : 0;+ const terrains = asset.terrains ?? [];+ const terrain = terrains[activeSet];+ const terrainColor = TERRAIN_COLORS[activeSet % TERRAIN_COLORS.length];const isSolid = (id: number): boolean =>drag?.ids.has(id) ? drag.on : asset.tiles[id]?.collision !== undefined;@@ -95,6 +120,19 @@ export function TilesetEditor() {TilesetCommands.setGrid({ ...patch, columns });};+ const tileTerrain = (id: number) => {+ const t = asset.tiles[id]?.terrain;+ return t && t.set === activeSet ? t : null;+ };+ const toggleBit = (id: number, bit: number) => {+ const cur = tileTerrain(id)?.mask ?? 0;+ TilesetCommands.setTileTerrain(id, activeSet, cur ^ bit);+ };+ const toggleMember = (id: number) => {+ if (tileTerrain(id)) TilesetCommands.setTileTerrain(id, null, 0);+ else TilesetCommands.setTileTerrain(id, activeSet, 0);+ };+const cells = [];if (texUrl && natural) {for (let row = 0; row < rows; row++) {@@ -102,25 +140,59 @@ export function TilesetEditor() {const id = row * cols + col + 1;const left = (mg + col * (tw + sp)) * zoom;const top = (mg + row * (th + sp)) * zoom;- cells.push(- <div- key={id}- className={'ts-cell' + (isSolid(id) ? ' is-solid' : '')}- style={{ left, top, width: tw * zoom, height: th * zoom }}- title={`#${id}`}- onPointerDown={(e) => {- e.preventDefault();- setDrag({ ids: new Set([id]), on: !isSolid(id) });- }}- onPointerEnter={() => {- if (dragRef.current) {- const ids = new Set(dragRef.current.ids);- ids.add(id);- setDrag({ ids, on: dragRef.current.on });- }- }}- />,- );+ const w = tw * zoom;+ const h = th * zoom;+ if (mode === 'collision') {+ cells.push(+ <div+ key={id}+ className={'ts-cell' + (isSolid(id) ? ' is-solid' : '')}+ style={{ left, top, width: w, height: h }}+ title={`#${id}`}+ onPointerDown={(e) => { e.preventDefault(); setDrag({ ids: new Set([id]), on: !isSolid(id) }); }}+ onPointerEnter={() => {+ if (dragRef.current) {+ const ids = new Set(dragRef.current.ids);+ ids.add(id);+ setDrag({ ids, on: dragRef.current.on });+ }+ }}+ />,+ );+ } else {+ const tt = tileTerrain(id);+ const showZones = hovered === id || tt != null;+ const cellStyle: CSSProperties = { left, top, width: w, height: h };+ if (tt) (cellStyle as Record<string, string | number>)['--tcolor'] = terrainColor;+ cells.push(+ <div+ key={id}+ className={'ts-cell ts-tcell' + (tt ? ' is-member' : '')}+ style={cellStyle}+ title={`#${id}`}+ onPointerEnter={() => setHovered(id)}+ onPointerLeave={() => setHovered((cur) => (cur === id ? null : cur))}+ >+ <button+ type="button" className="ts-zone ts-zone-c"+ title="该瓦片属于此地形"+ onClick={() => toggleMember(id)}+ />+ {showZones && terrain && ZONES.filter((z) => terrain.mode === 'corner' || !z.corner).map((z) => {+ const on = ((tt?.mask ?? 0) & z.bit) !== 0;+ return (+ <button+ key={z.bit}+ type="button"+ className={'ts-zone' + (on ? ' is-on' : '') + (z.corner ? ' is-corner' : '')}+ style={{ left: `${z.gx * 33.34}%`, top: `${z.gy * 33.34}%` }}+ onClick={() => toggleBit(id, z.bit)}+ />+ );+ })}+ </div>,+ );+ }}}}@@ -135,19 +207,67 @@ export function TilesetEditor() {<GridField label="Margin" value={mg} onCommit={(n) => editGrid({ margin: n })} /><GridField label="Spacing" value={sp} onCommit={(n) => editGrid({ spacing: n })} /><span className="ts-sep" />+ <div className="ts-modes">+ <button type="button" className={mode === 'collision' ? 'is-active' : ''} onClick={() => setMode('collision')}>碰撞</button>+ <button type="button" className={mode === 'terrain' ? 'is-active' : ''} onClick={() => setMode('terrain')}>地形</button>+ </div>+ <span className="ts-sep" /><label className="ts-field"><span>Zoom</span><input type="range" min={1} max={8} step={1} value={zoom}onChange={(e) => setZoom(Number(e.target.value))} /></label><span className="ts-grow" />- <span className="ts-stat">{cols}×{rows} · {solidCount} solid</span>+ <span className="ts-stat">+ {cols}×{rows}{mode === 'collision' ? ` · ${solidCount} solid` : ''}+ </span><button type="button" className="ts-save" onClick={() => void TilesetCommands.save()} disabled={!meta.dirty}><Save size={13} /> 保存{meta.dirty ? ' •' : ''}</button></div>- <div className="ts-canvas" onPointerUp={commitDrag} onPointerLeave={commitDrag}>+ {mode === 'terrain' && (+ <div className="ts-terrains">+ {terrains.map((t, i) => (+ <button+ key={i}+ type="button"+ className={'ts-terrain' + (i === activeSet ? ' is-active' : '')}+ onClick={() => setActiveSet(i)}+ >+ <span className="ts-tswatch" style={{ background: TERRAIN_COLORS[i % TERRAIN_COLORS.length] }} />+ {t.name}+ <span className="ts-tmode">{t.mode === 'corner' ? '角' : '边'}</span>+ </button>+ ))}+ <button type="button" className="ts-terrain ts-add" title="新建地形"+ onClick={() => { TilesetCommands.addTerrain('', 'edge'); setActiveSet(terrains.length); setMode('terrain'); }}>+ <Plus size={13} />+ </button>+ {terrain && (+ <div className="ts-tedit">+ <input+ className="ts-tname" value={terrain.name}+ onChange={(e) => TilesetCommands.updateTerrain(activeSet, { name: e.target.value })}+ />+ <select+ value={terrain.mode}+ onChange={(e) => TilesetCommands.updateTerrain(activeSet, { mode: e.target.value as TerrainMode })}+ >+ <option value="edge">边 (4-bit)</option>+ <option value="corner">角 (blob)</option>+ </select>+ <button type="button" className="ts-trm" title="删除地形"+ onClick={() => { TilesetCommands.removeTerrain(activeSet); setActiveSet(0); }}>+ <Trash2 size={13} />+ </button>+ </div>+ )}+ </div>+ )}++ <div className="ts-canvas" onPointerUp={mode === 'collision' ? commitDrag : undefined}+ onPointerLeave={mode === 'collision' ? commitDrag : undefined}>{!texUrl ? (<div className="ts-warn">纹理未找到(引用 {String(asset.texture) || '空'})</div>) : (diff --git a/desktop/src/store/tilemapPaintStore.ts b/desktop/src/store/tilemapPaintStore.tsindex 347c7d18d..2226c8d35 100644--- a/desktop/src/store/tilemapPaintStore.ts+++ b/desktop/src/store/tilemapPaintStore.ts@@ -2,32 +2,56 @@// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team/*** @file tilemapPaintStore.ts- * @brief Transient tilemap-painting state: the active tileset- * palette, the selected brush tile, and the active paint tool. When a tool is- * set AND a TilemapLayer entity is selected, the Viewport paints instead of+ * @brief Transient tilemap-painting state: the active tileset palette (path + parsed+ * asset), the brush (a {@link TileStamp}, so multi-tile selection + flip + rotate+ * flow through one model), the active terrain set, and the active paint tool. When+ * a tool is set AND a TilemapLayer is selected, the Viewport paints instead of* selecting. Editor-session state — never serialized.*/import { create } from 'zustand';+import {+ type TileStamp, type TilesetAsset,+ singleStamp, flipStampH, flipStampV, rotateStampCW, encodeTile,+} from 'esengine';-export type PaintTool = 'brush' | 'erase' | 'rect' | 'eyedropper';+export type PaintTool = 'brush' | 'erase' | 'rect' | 'eyedropper' | 'terrain';interface TilemapPaintState {- /** Active `.estileset` palette (project-relative path), or null. */- tilesetPath: string | null;- /** The tile id to paint (1-based; 0 = empty/erase). */- brushTileId: number;- /** The active tool; null = not painting (the Viewport selects normally). */- tool: PaintTool | null;- setTileset(path: string | null): void;- setBrush(tileId: number): void;- setTool(tool: PaintTool | null): void;+ /** Active `.estileset` palette (project-relative path), or null. */+ tilesetPath: string | null;+ /** The parsed active palette asset (kept here so the viewport terrain tool can resolve). */+ tilesetAsset: TilesetAsset | null;+ /** The active brush pattern. A 1×1 stamp is the classic single-tile brush. */+ stamp: TileStamp;+ /** The active terrain set index (for the terrain tool). */+ terrainSet: number;+ /** The active tool; null = not painting (the Viewport selects normally). */+ tool: PaintTool | null;+ setTileset(path: string | null): void;+ setTilesetAsset(asset: TilesetAsset | null): void;+ setStamp(stamp: TileStamp): void;+ /** Set a 1×1 brush of one tile id (palette single-click; loses any flip flags). */+ setBrushTile(tileId: number): void;+ setTerrainSet(set: number): void;+ flipH(): void;+ flipV(): void;+ rotateCW(): void;+ setTool(tool: PaintTool | null): void;}export const useTilemapPaint = create<TilemapPaintState>((set) => ({- tilesetPath: null,- brushTileId: 1,- tool: null,- setTileset: (tilesetPath) => set({ tilesetPath }),- setBrush: (brushTileId) => set({ brushTileId }),- setTool: (tool) => set({ tool }),+ tilesetPath: null,+ tilesetAsset: null,+ stamp: singleStamp(encodeTile(1)),+ terrainSet: 0,+ tool: null,+ setTileset: (tilesetPath) => set({ tilesetPath }),+ setTilesetAsset: (tilesetAsset) => set({ tilesetAsset }),+ setStamp: (stamp) => set({ stamp }),+ setBrushTile: (tileId) => set({ stamp: singleStamp(encodeTile(tileId)) }),+ setTerrainSet: (terrainSet) => set({ terrainSet }),+ flipH: () => set((s) => ({ stamp: flipStampH(s.stamp) })),+ flipV: () => set((s) => ({ stamp: flipStampV(s.stamp) })),+ rotateCW: () => set((s) => ({ stamp: rotateStampCW(s.stamp) })),+ setTool: (tool) => set({ tool }),}));diff --git a/desktop/src/theme/tilemap.css b/desktop/src/theme/tilemap.cssindex c4130fafd..e64230eb4 100644--- a/desktop/src/theme/tilemap.css+++ b/desktop/src/theme/tilemap.css@@ -21,6 +21,7 @@flex: 0 0 auto;}.tp-grow { flex: 1 1 auto; }+.tp-sep { width: 1px; align-self: stretch; margin: 2px 4px; background: var(--line, #2a2d33); }.tp-brush { color: var(--text-faint, #6b717c); font-variant-numeric: tabular-nums; }.tp-tool {@@ -51,6 +52,32 @@.tp-atlas { position: relative; }.tp-img { display: block; image-rendering: pixelated; user-select: none; }+.tp-terrains {+ flex: 1 1 auto;+ overflow: auto;+ padding: 10px;+ display: flex;+ flex-direction: column;+ gap: 4px;+ background: var(--srf-0, #101216);+}+.tp-terrain {+ display: inline-flex;+ align-items: center;+ gap: 7px;+ background: var(--control, #24272d);+ border: 1px solid var(--line, #2a2d33);+ border-radius: 3px;+ color: var(--text-dim, #9aa0aa);+ padding: 5px 9px;+ cursor: pointer;+ font: inherit;+ text-align: left;+}+.tp-terrain.is-active { border-color: var(--star, #4c8fd6); color: var(--text, #d6d9de); }+.tp-tswatch { width: 12px; height: 12px; border-radius: 2px; display: inline-block; }+.tp-warn { color: var(--text-faint, #6b717c); padding: 12px; font-size: 11px; }+.tp-cell {position: absolute;box-sizing: border-box;diff --git a/desktop/src/theme/tileset.css b/desktop/src/theme/tileset.cssindex c95dc6919..784bae022 100644--- a/desktop/src/theme/tileset.css+++ b/desktop/src/theme/tileset.css@@ -92,6 +92,91 @@}.ts-cell.is-solid:hover { background: rgba(240, 100, 90, 0.5); }+/* Mode switch (collision / terrain) */+.ts-modes { display: inline-flex; border: 1px solid var(--line, #2a2d33); border-radius: 3px; overflow: hidden; }+.ts-modes button {+ background: var(--control, #24272d);+ color: var(--text-dim, #9aa0aa);+ border: none;+ padding: 3px 10px;+ cursor: pointer;+ font: inherit;+}+.ts-modes button.is-active { background: var(--star, #4c8fd6); color: var(--on-accent, #fff); }++/* Terrain set bar */+.ts-terrains {+ display: flex;+ align-items: center;+ gap: 6px;+ flex-wrap: wrap;+ padding: 6px 10px;+ border-bottom: 1px solid var(--line, #2a2d33);+ background: var(--srf-2, #1b1e23);+ flex: 0 0 auto;+}+.ts-terrain {+ display: inline-flex;+ align-items: center;+ gap: 5px;+ background: var(--control, #24272d);+ border: 1px solid var(--line, #2a2d33);+ border-radius: 3px;+ color: var(--text-dim, #9aa0aa);+ padding: 3px 8px;+ cursor: pointer;+ font: inherit;+}+.ts-terrain.is-active { border-color: var(--star, #4c8fd6); color: var(--text, #d6d9de); }+.ts-tswatch { width: 11px; height: 11px; border-radius: 2px; display: inline-block; }+.ts-tmode { color: var(--text-faint, #6b717c); font-size: 10px; }+.ts-add { padding: 3px 6px; }+.ts-tedit { display: inline-flex; align-items: center; gap: 6px; margin-left: auto; }+.ts-tname {+ width: 110px;+ background: var(--inset, #0f1115);+ border: 1px solid var(--line, #2a2d33);+ border-radius: 3px;+ color: var(--text, #d6d9de);+ padding: 2px 6px;+ font: inherit;+}+.ts-tedit select {+ background: var(--inset, #0f1115);+ border: 1px solid var(--line, #2a2d33);+ border-radius: 3px;+ color: var(--text, #d6d9de);+ padding: 2px 4px;+ font: inherit;+}+.ts-trm {+ background: none;+ border: 1px solid var(--line, #2a2d33);+ border-radius: 3px;+ color: var(--text-dim, #9aa0aa);+ padding: 3px 5px;+ cursor: pointer;+}+.ts-trm:hover { color: #f0645a; border-color: #f0645a; }++/* Terrain peering cell: member highlight + clickable 3×3 zones */+.ts-tcell.is-member { background: color-mix(in srgb, var(--tcolor) 26%, transparent); border-color: var(--tcolor); }+.ts-zone {+ position: absolute;+ width: 33.34%;+ height: 33.34%;+ margin: 0;+ padding: 0;+ background: transparent;+ border: none;+ cursor: pointer;+}+.ts-zone:hover { background: rgba(255, 255, 255, 0.18); }+.ts-zone.is-on { background: rgba(76, 143, 214, 0.55); box-shadow: inset 0 0 0 1px rgba(255, 255, 255, 0.4); }+.ts-zone.is-corner.is-on { background: rgba(214, 196, 76, 0.6); }+.ts-zone-c { left: 33.34%; top: 33.34%; }+.ts-zone-c:hover { background: rgba(255, 255, 255, 0.1); }+.ts-empty,.ts-warn {display: flex;diff --git a/desktop/src/tileset/TilesetCommands.ts b/desktop/src/tileset/TilesetCommands.tsindex e1bdd0289..4ae11eaa9 100644--- a/desktop/src/tileset/TilesetCommands.ts+++ b/desktop/src/tileset/TilesetCommands.ts@@ -8,7 +8,7 @@*/import { serializeTileset } from 'esengine';-import type { TilesetAsset } from 'esengine';+import type { TilesetAsset, TilesetTerrain, TerrainMode } from 'esengine';import { TilesetDocument } from './TilesetDocument';import { Toasts } from '@/store/Toasts';@@ -17,7 +17,7 @@ type GridPatch = Partial<Pick<TilesetAsset, 'tileWidth' | 'tileHeight' | 'margin/** Drop a tile entry that no longer carries any metadata, keeping the map sparse. */function pruneEmpty(asset: TilesetAsset, id: number): void {const t = asset.tiles[id];- if (t && !t.collision && !t.properties && !t.animation) delete asset.tiles[id];+ if (t && !t.collision && !t.properties && !t.animation && !t.terrain) delete asset.tiles[id];}export const TilesetCommands = {@@ -50,6 +50,56 @@ export const TilesetCommands = {});},+ /** Add a terrain (autotile) set; returns the new set's index. */+ addTerrain(name: string, mode: TerrainMode): void {+ TilesetDocument.edit('Add Terrain', (a) => {+ const terrains = a.terrains ?? (a.terrains = []);+ terrains.push({ name: name || `Terrain ${terrains.length + 1}`, mode });+ });+ },++ /** Edit a terrain set's name / mode / color. */+ updateTerrain(set: number, patch: Partial<TilesetTerrain>): void {+ TilesetDocument.edit('Edit Terrain', (a) => {+ const t = a.terrains?.[set];+ if (!t) return;+ if (typeof patch.name === 'string') t.name = patch.name;+ if (patch.mode === 'edge' || patch.mode === 'corner') t.mode = patch.mode;+ if (typeof patch.color === 'string') t.color = patch.color;+ });+ },++ /** Remove a terrain set, dropping its tiles' membership and reindexing higher sets. */+ removeTerrain(set: number): void {+ TilesetDocument.edit('Remove Terrain', (a) => {+ if (!a.terrains?.[set]) return;+ a.terrains.splice(set, 1);+ for (const key of Object.keys(a.tiles)) {+ const id = Number(key);+ const tt = a.tiles[id].terrain;+ if (!tt) continue;+ if (tt.set === set) { delete a.tiles[id].terrain; pruneEmpty(a, id); }+ else if (tt.set > set) tt.set -= 1;+ }+ if (a.terrains.length === 0) delete a.terrains;+ });+ },++ /**+ * Set a tile's terrain membership + peering mask as ONE undo step. `set === null`+ * removes the tile from any terrain.+ */+ setTileTerrain(id: number, set: number | null, mask: number): void {+ if (id <= 0) return;+ TilesetDocument.edit('Edit Tile Terrain', (a) => {+ if (set === null) {+ if (a.tiles[id]?.terrain) { delete a.tiles[id].terrain; pruneEmpty(a, id); }+ return;+ }+ a.tiles[id] = { ...(a.tiles[id] ?? {}), terrain: { set, mask: mask & 0xff } };+ });+ },+/** Persist the open tileset to its file. */async save(): Promise<void> {const asset = TilesetDocument.asset;diff --git a/desktop/src/tools/tileTools.ts b/desktop/src/tools/tileTools.tsindex 8b46fa8b1..7829591c4 100644--- a/desktop/src/tools/tileTools.ts+++ b/desktop/src/tools/tileTools.ts@@ -3,10 +3,15 @@/*** @file tileTools.ts* @brief The tilemap paint tools — brush / erase / rect / eyedropper. Active only- * when a TilemapLayer is selected (the host resolves that); each operates- * on the selected layer via SceneCommands' tile-paint stroke API.+ * when a TilemapLayer is selected (the host resolves that); each operates on the+ * selected layer via SceneCommands' tile-paint stroke API. The brush is a+ * {@link TileStamp}, so a single click stamps a 1×1 tile and a palette marquee+ * stamps a whole pattern (with per-cell flip/rotate flags preserved).*/-import { TilemapAPI } from 'esengine';+import {+ TilemapAPI, tileIdOf, encodeTile, singleStamp, type TileStamp,+ buildTerrainIndices, resolveAutotile, TERRAIN_NEIGHBORS, type TerrainIndices,+} from 'esengine';import { ViewportController } from '@/engine/ViewportController';import { SceneCommands, type TilePaint } from '@/engine/SceneCommands';import { SceneModel } from '@/engine/SceneModel';@@ -26,20 +31,38 @@ function cursorTile(clientX: number, clientY: number, sourceId: number): { x: nu}const selectedTilemap = (): number | null => useSelection.getState().selectedId;+const activeStamp = (): TileStamp => useTilemapPaint.getState().stamp;-/** Brush (paints brushTileId) / Erase (paints 0): a live stroke, one undo step. */-function makeBrushTool(id: string, erase: boolean): EditorTool {+/** Edits for the non-empty cells of `stamp` anchored (top-left) at tile (ox, oy). */+function stampEdits(stamp: TileStamp, ox: number, oy: number): TilePaint[] {+ const edits: TilePaint[] = [];+ for (let dy = 0; dy < stamp.h; dy++) {+ for (let dx = 0; dx < stamp.w; dx++) {+ const raw = stamp.cells[dy * stamp.w + dx];+ if (tileIdOf(raw) === 0) continue; // sparse — empty cells leave the map untouched+ edits.push({ x: ox + dx, y: oy + dy, tileId: raw });+ }+ }+ return edits;+}++/** Brush: stamps the active pattern as a live stroke (one undo step). */+function makeBrushTool(): EditorTool {let stroke: { sourceId: number; last: string } | null = null;- const tileId = () => (erase ? 0 : useTilemapPaint.getState().brushTileId);+ const stampAt = (id: number, ox: number, oy: number) => {+ for (const e of stampEdits(activeStamp(), ox, oy)) {+ SceneCommands.paintTileLive(id, e.x, e.y, e.tileId);+ }+ };return {- id,+ id: 'tilemap.brush',onPointerDown(p, ctx) {const selId = selectedTilemap();if (selId == null) return false;const tile = cursorTile(p.clientX, p.clientY, selId);if (!tile) return false;SceneCommands.beginTilePaint(selId);- SceneCommands.paintTileLive(selId, tile.x, tile.y, tileId());+ stampAt(selId, tile.x, tile.y);stroke = { sourceId: selId, last: `${tile.x},${tile.y}` };ctx.capture(p.pointerId);return true;@@ -50,7 +73,7 @@ function makeBrushTool(id: string, erase: boolean): EditorTool {if (!tile) return;const key = `${tile.x},${tile.y}`;if (key === stroke.last) return;- SceneCommands.paintTileLive(stroke.sourceId, tile.x, tile.y, tileId());+ stampAt(stroke.sourceId, tile.x, tile.y);stroke.last = key;},onPointerUp(p, ctx) {@@ -68,7 +91,46 @@ function makeBrushTool(id: string, erase: boolean): EditorTool {};}-/** Rect fill: drag a rectangle, fill it with brushTileId on release (one step). */+/** Erase: clears the cell under the cursor — a live stroke, one undo step. */+function makeEraseTool(): EditorTool {+ let stroke: { sourceId: number; last: string } | null = null;+ return {+ id: 'tilemap.erase',+ onPointerDown(p, ctx) {+ const selId = selectedTilemap();+ if (selId == null) return false;+ const tile = cursorTile(p.clientX, p.clientY, selId);+ if (!tile) return false;+ SceneCommands.beginTilePaint(selId);+ SceneCommands.paintTileLive(selId, tile.x, tile.y, 0);+ stroke = { sourceId: selId, last: `${tile.x},${tile.y}` };+ ctx.capture(p.pointerId);+ return true;+ },+ onPointerMove(p) {+ if (!stroke) return;+ const tile = cursorTile(p.clientX, p.clientY, stroke.sourceId);+ if (!tile) return;+ const key = `${tile.x},${tile.y}`;+ if (key === stroke.last) return;+ SceneCommands.paintTileLive(stroke.sourceId, tile.x, tile.y, 0);+ stroke.last = key;+ },+ onPointerUp(p, ctx) {+ if (!stroke) return;+ ctx.release(p.pointerId);+ SceneCommands.endTilePaint();+ stroke = null;+ },+ cancel() {+ if (!stroke) return;+ SceneCommands.endTilePaint();+ stroke = null;+ },+ };+}++/** Rect fill: drag a rectangle, tile the active stamp across it on release (one step). */function makeRectTool(): EditorTool {let stroke: { sourceId: number; startX: number; startY: number } | null = null;return {@@ -94,10 +156,16 @@ function makeRectTool(): EditorTool {const x1 = Math.max(stroke.startX, tile.x);const y0 = Math.min(stroke.startY, tile.y);const y1 = Math.max(stroke.startY, tile.y);- const tileId = useTilemapPaint.getState().brushTileId;+ const stamp = activeStamp();const edits: TilePaint[] = [];- for (let y = y0; y <= y1; y++) for (let x = x0; x <= x1; x++) edits.push({ x, y, tileId });- SceneCommands.paintTiles(stroke.sourceId, edits);+ for (let y = y0; y <= y1; y++) {+ for (let x = x0; x <= x1; x++) {+ const raw = stamp.cells[((y - y0) % stamp.h) * stamp.w + ((x - x0) % stamp.w)];+ if (tileIdOf(raw) === 0) continue;+ edits.push({ x, y, tileId: raw });+ }+ }+ if (edits.length > 0) SceneCommands.paintTiles(stroke.sourceId, edits);}stroke = null;},@@ -107,7 +175,80 @@ function makeRectTool(): EditorTool {};}-/** Eyedropper: one-shot — read the tile under the cursor into the active brush. */+/**+ * Terrain brush: paint a logical terrain and autotile. Each painted cell joins the active+ * terrain; the cell and its 8 neighbours are re-resolved against the tileset's terrain+ * rules, so the right edge/corner tile is chosen automatically. A cell's terrain is the+ * in-stroke assignment if painted, else reverse-derived from its current tile.+ */+function makeTerrainTool(): EditorTool {+ let stroke:+ | { sourceId: number; rt: number; set: number; indices: TerrainIndices; assigned: Map<string, number> }+ | null = null;++ const terrainAt = (s: NonNullable<typeof stroke>, x: number, y: number): number | null => {+ const key = `${x},${y}`;+ if (s.assigned.has(key)) return s.assigned.get(key)!;+ const id = tileIdOf(TilemapAPI.getTile(s.rt, x, y));+ return s.indices.tileTerrain.get(id) ?? null;+ };++ const recompute = (s: NonNullable<typeof stroke>, x: number, y: number) => {+ const set = terrainAt(s, x, y);+ if (set == null) return;+ const index = s.indices.sets.get(set);+ if (!index) return;+ const neighbors = TERRAIN_NEIGHBORS.map((n) => terrainAt(s, x + n.dx, y + n.dy) === set);+ const tileId = resolveAutotile(index, neighbors);+ if (tileId > 0) SceneCommands.paintTileLive(s.sourceId, x, y, encodeTile(tileId));+ };++ const stampTerrain = (s: NonNullable<typeof stroke>, x: number, y: number) => {+ s.assigned.set(`${x},${y}`, s.set);+ recompute(s, x, y);+ for (const n of TERRAIN_NEIGHBORS) recompute(s, x + n.dx, y + n.dy);+ };++ return {+ id: 'tilemap.terrain',+ onPointerDown(p, ctx) {+ const selId = selectedTilemap();+ if (selId == null) return false;+ const rt = SceneModel.runtimeFor(selId);+ const ps = useTilemapPaint.getState();+ const asset = ps.tilesetAsset;+ if (rt == null || !asset) return false;+ const tile = cursorTile(p.clientX, p.clientY, selId);+ if (!tile) return false;+ const indices = buildTerrainIndices(asset);+ if (!indices.sets.has(ps.terrainSet)) return false; // active terrain has no tiles yet+ SceneCommands.beginTilePaint(selId);+ stroke = { sourceId: selId, rt, set: ps.terrainSet, indices, assigned: new Map() };+ stampTerrain(stroke, tile.x, tile.y);+ ctx.capture(p.pointerId);+ return true;+ },+ onPointerMove(p) {+ if (!stroke) return;+ const tile = cursorTile(p.clientX, p.clientY, stroke.sourceId);+ if (!tile || stroke.assigned.has(`${tile.x},${tile.y}`)) return;+ stampTerrain(stroke, tile.x, tile.y);+ },+ onPointerUp(p, ctx) {+ if (!stroke) return;+ ctx.release(p.pointerId);+ SceneCommands.endTilePaint();+ stroke = null;+ },+ cancel() {+ if (!stroke) return;+ SceneCommands.endTilePaint();+ stroke = null;+ },+ };+}++/** Eyedropper: one-shot — read the raw cell (id + flip flags) under the cursor into the brush. */const eyedropperTool: EditorTool = {id: 'tilemap.eyedropper',onPointerDown(p) {@@ -116,8 +257,8 @@ const eyedropperTool: EditorTool = {const tile = cursorTile(p.clientX, p.clientY, selId);if (!tile) return false;const rt = SceneModel.runtimeFor(selId);- const id = rt != null ? TilemapAPI.getTile(rt, tile.x, tile.y) : 0;- if (id > 0) useTilemapPaint.getState().setBrush(id);+ const raw = rt != null ? TilemapAPI.getTile(rt, tile.x, tile.y) : 0;+ if (tileIdOf(raw) > 0) useTilemapPaint.getState().setStamp(singleStamp(raw));return false; // no ongoing stroke},onPointerMove() {},@@ -126,10 +267,11 @@ const eyedropperTool: EditorTool = {/** Tile tools keyed by PaintTool (brush/erase/rect/eyedropper). */export const TILE_TOOLS: Record<PaintTool, EditorTool> = {- brush: makeBrushTool('tilemap.brush', false),- erase: makeBrushTool('tilemap.erase', true),+ brush: makeBrushTool(),+ erase: makeEraseTool(),rect: makeRectTool(),eyedropper: eyedropperTool,+ terrain: makeTerrainTool(),};export type { PointerInput };diff --git a/desktop/tests/editor-tools.test.ts b/desktop/tests/editor-tools.test.tsindex 63b899c5d..3b2679ae2 100644--- a/desktop/tests/editor-tools.test.ts+++ b/desktop/tests/editor-tools.test.ts@@ -24,7 +24,7 @@ describe('editor tool registry', () => {});it('has the tile tools keyed by PaintTool', () => {- for (const k of ['brush', 'erase', 'rect', 'eyedropper'] as const) {+ for (const k of ['brush', 'erase', 'rect', 'eyedropper', 'terrain'] as const) {expect(TILE_TOOLS[k]).toBeDefined();expect(implementsContract(TILE_TOOLS[k])).toBe(true);}diff --git a/desktop/tests/tilemap-paint-store.test.ts b/desktop/tests/tilemap-paint-store.test.tsnew file mode 100644index 000000000..04d9db57b--- /dev/null+++ b/desktop/tests/tilemap-paint-store.test.ts@@ -0,0 +1,49 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file The tilemap paint store's brush is a TileStamp; flip/rotate transform it in+ * place. Guards the store wiring over the SDK stamp algebra (which is unit-tested+ * separately) — the painter + viewport tools read `stamp` straight off this store.+ */+import { describe, it, expect, beforeEach } from 'vitest';+import { tileIdOf, tileFlagsOf } from 'esengine';+import { useTilemapPaint } from '@/store/tilemapPaintStore';++describe('tilemap paint store', () => {+ beforeEach(() => {+ useTilemapPaint.getState().setBrushTile(1);+ });++ it('setBrushTile makes a 1×1 stamp of that id with no flags', () => {+ useTilemapPaint.getState().setBrushTile(7);+ const s = useTilemapPaint.getState().stamp;+ expect(s).toMatchObject({ w: 1, h: 1 });+ expect(tileIdOf(s.cells[0])).toBe(7);+ expect(tileFlagsOf(s.cells[0])).toEqual({ flipH: false, flipV: false, flipD: false });+ });++ it('setStamp stores a multi-tile pattern', () => {+ useTilemapPaint.getState().setStamp({ w: 2, h: 1, cells: [1, 2] });+ expect(useTilemapPaint.getState().stamp).toEqual({ w: 2, h: 1, cells: [1, 2] });+ });++ it('flipH flips the stamp in place (4 ops over a 2×1 restores it)', () => {+ useTilemapPaint.getState().setStamp({ w: 2, h: 1, cells: [1, 2] });+ useTilemapPaint.getState().flipH();+ const s = useTilemapPaint.getState().stamp;+ expect(tileIdOf(s.cells[0])).toBe(2);+ expect(tileFlagsOf(s.cells[0]).flipH).toBe(true);+ useTilemapPaint.getState().flipH();+ expect(useTilemapPaint.getState().stamp).toEqual({ w: 2, h: 1, cells: [1, 2] });+ });++ it('rotateCW transposes dims; four rotations restore the brush', () => {+ useTilemapPaint.getState().setStamp({ w: 2, h: 1, cells: [1, 2] });+ useTilemapPaint.getState().rotateCW();+ expect(useTilemapPaint.getState().stamp).toMatchObject({ w: 1, h: 2 });+ useTilemapPaint.getState().rotateCW();+ useTilemapPaint.getState().rotateCW();+ useTilemapPaint.getState().rotateCW();+ expect(useTilemapPaint.getState().stamp).toEqual({ w: 2, h: 1, cells: [1, 2] });+ });+});diff --git a/sdk/src/core-content.ts b/sdk/src/core-content.tsindex c8ba99637..49fa8d81d 100644--- a/sdk/src/core-content.ts+++ b/sdk/src/core-content.ts@@ -287,6 +287,38 @@ export {serializeTileset,createTileset,collidableTileIds,+ TB_N,+ TB_E,+ TB_S,+ TB_W,+ TB_NE,+ TB_SE,+ TB_SW,+ TB_NW,+ TERRAIN_NEIGHBORS,+ normalizeCornerMask,+ canonicalMask,+ buildTerrainIndices,+ resolveAutotile,+ TILE_ID_MASK,+ TILE_FLIP_H,+ TILE_FLIP_V,+ TILE_FLIP_D,+ TILE_FLAGS_MASK,+ encodeTile,+ tileIdOf,+ tileFlagsOf,+ orientationPerm,+ flipFlagsH,+ flipFlagsV,+ rotateFlagsCW,+ singleStamp,+ isEmptyStamp,+ flipStampH,+ flipStampV,+ rotateStampCW,+ type TileFlags,+ type TileStamp,type TilemapData,type TilemapLayerData,type TiledMapData,@@ -300,6 +332,11 @@ export {type TilesetTile,type TilesetCollision,type TilesetAnimFrame,+ type TerrainMode,+ type TilesetTerrain,+ type TilesetTileTerrain,+ type TerrainIndex,+ type TerrainIndices,} from './tilemap';// =============================================================================diff --git a/sdk/src/tilemap/autotile.ts b/sdk/src/tilemap/autotile.tsnew file mode 100644index 000000000..40cf54c80--- /dev/null+++ b/sdk/src/tilemap/autotile.ts@@ -0,0 +1,123 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file autotile.ts+ * @brief Terrain autotiling: pick a tile from a `.estileset` terrain set by how a cell+ * peers with its same-terrain neighbours. Pure (no engine deps) so the painter+ * and tests share one resolver.+ *+ * Two modes (see {@link TerrainMode}): `edge` matches the 4 sides (N/E/S/W → 16 tiles),+ * `corner` is the 8-bit "corners and sides" blob — a corner peering bit only counts when+ * both of its adjacent sides also peer (the classic 47-tile reduction). When no tile has+ * the exact mask, the nearest by Hamming distance is used, so a partial set still paints.+ */++import type { TilesetAsset, TerrainMode } from './tilesetAsset';++// Peering-direction bits. Sides are the low nibble so `& SIDE_BITS` keeps edge masks.+export const TB_N = 1;+export const TB_E = 2;+export const TB_S = 4;+export const TB_W = 8;+export const TB_NE = 16;+export const TB_SE = 32;+export const TB_SW = 64;+export const TB_NW = 128;++const SIDE_BITS = TB_N | TB_E | TB_S | TB_W;++/**+ * The 8 neighbour offsets (tile grid, y down) paired with their peering bit. Index order+ * is the contract for {@link resolveAutotile}'s `neighbors` argument.+ */+export const TERRAIN_NEIGHBORS: ReadonlyArray<{ dx: number; dy: number; bit: number }> = [+ { dx: 0, dy: -1, bit: TB_N },+ { dx: 1, dy: -1, bit: TB_NE },+ { dx: 1, dy: 0, bit: TB_E },+ { dx: 1, dy: 1, bit: TB_SE },+ { dx: 0, dy: 1, bit: TB_S },+ { dx: -1, dy: 1, bit: TB_SW },+ { dx: -1, dy: 0, bit: TB_W },+ { dx: -1, dy: -1, bit: TB_NW },+];++/** Drop corner bits whose two adjacent sides don't both peer (the blob rule). */+export function normalizeCornerMask(mask: number): number {+ let m = mask;+ if ((m & TB_N) === 0 || (m & TB_E) === 0) m &= ~TB_NE;+ if ((m & TB_S) === 0 || (m & TB_E) === 0) m &= ~TB_SE;+ if ((m & TB_S) === 0 || (m & TB_W) === 0) m &= ~TB_SW;+ if ((m & TB_N) === 0 || (m & TB_W) === 0) m &= ~TB_NW;+ return m;+}++/** Canonicalize a raw peering mask for a mode (edge → sides only, corner → blob rule). */+export function canonicalMask(mode: TerrainMode, mask: number): number {+ return mode === 'corner' ? normalizeCornerMask(mask) : mask & SIDE_BITS;+}++/** A terrain set's resolver table: canonical peering mask → the tile id to draw. */+export interface TerrainIndex {+ mode: TerrainMode;+ byMask: Map<number, number>;+}++/** Built lookup over a tileset's terrains: per-set resolver + reverse tile→set. */+export interface TerrainIndices {+ /** setIndex → its {@link TerrainIndex}. */+ sets: Map<number, TerrainIndex>;+ /** tile id → the terrain set it belongs to (for reverse-deriving a painted cell's terrain). */+ tileTerrain: Map<number, number>;+}++/** Build the terrain resolver tables for a tileset (first tile wins a duplicated mask). */+export function buildTerrainIndices(asset: TilesetAsset): TerrainIndices {+ const sets = new Map<number, TerrainIndex>();+ const tileTerrain = new Map<number, number>();+ const terrains = asset.terrains ?? [];+ for (const key of Object.keys(asset.tiles)) {+ const id = Number(key);+ const t = asset.tiles[id].terrain;+ if (!t) continue;+ tileTerrain.set(id, t.set);+ const mode: TerrainMode = terrains[t.set]?.mode ?? 'edge';+ let index = sets.get(t.set);+ if (!index) {+ index = { mode, byMask: new Map() };+ sets.set(t.set, index);+ }+ const mask = canonicalMask(mode, t.mask);+ if (!index.byMask.has(mask)) index.byMask.set(mask, id);+ }+ return { sets, tileTerrain };+}++function popcount(n: number): number {+ let c = 0;+ for (let v = n; v !== 0; v &= v - 1) c++;+ return c;+}++/**+ * Pick the tile for a cell given which of its 8 neighbours are the same terrain.+ * `neighbors` is indexed by {@link TERRAIN_NEIGHBORS} order. Returns 0 if the set is empty.+ */+export function resolveAutotile(index: TerrainIndex, neighbors: readonly boolean[]): number {+ let mask = 0;+ for (let i = 0; i < TERRAIN_NEIGHBORS.length; i++) {+ if (neighbors[i]) mask |= TERRAIN_NEIGHBORS[i].bit;+ }+ mask = canonicalMask(index.mode, mask);+ const exact = index.byMask.get(mask);+ if (exact !== undefined) return exact;+ let best = 0;+ let bestDist = Infinity;+ for (const [m, id] of index.byMask) {+ const d = popcount(m ^ mask);+ if (d < bestDist) {+ bestDist = d;+ best = id;+ }+ }+ return best;+}diff --git a/sdk/src/tilemap/index.ts b/sdk/src/tilemap/index.tsindex c21d51ae3..2e48a8f42 100644--- a/sdk/src/tilemap/index.ts+++ b/sdk/src/tilemap/index.ts@@ -12,14 +12,28 @@ export {} from './tiledLoader';export { mergeCollisionTiles, type MergedRect } from './collisionMerge';export { decodeTilemapChunks, CHUNK_SIZE, type DecodedChunk } from './chunkCodec';+export {+ TILE_ID_MASK, TILE_FLIP_H, TILE_FLIP_V, TILE_FLIP_D, TILE_FLAGS_MASK,+ encodeTile, tileIdOf, tileFlagsOf, orientationPerm,+ flipFlagsH, flipFlagsV, rotateFlagsCW, type TileFlags,+} from './tileBits';+export {+ singleStamp, isEmptyStamp, flipStampH, flipStampV, rotateStampCW, type TileStamp,+} from './tileStamp';export {TILESET_FORMAT_VERSION, parseTileset, serializeTileset, createTileset, collidableTileIds,type TilesetAsset, type TilesetTile, type TilesetCollision, type TilesetAnimFrame,+ type TerrainMode, type TilesetTerrain, type TilesetTileTerrain,} from './tilesetAsset';export {resolveTilesetModel,type ResolvedTileset, type TilesetModel, type TilesetModelSlot,} from './tilesetResolve';+export {+ TB_N, TB_E, TB_S, TB_W, TB_NE, TB_SE, TB_SW, TB_NW, TERRAIN_NEIGHBORS,+ normalizeCornerMask, canonicalMask, buildTerrainIndices, resolveAutotile,+ type TerrainIndex, type TerrainIndices,+} from './autotile';export {registerTilemapSource, getTilemapSource, clearTilemapSourceCache,registerResolvedTileset, getResolvedTileset, clearResolvedTilesetCache,diff --git a/sdk/src/tilemap/tileBits.ts b/sdk/src/tilemap/tileBits.tsnew file mode 100644index 000000000..4740a2703--- /dev/null+++ b/sdk/src/tilemap/tileBits.ts@@ -0,0 +1,111 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file tileBits.ts+ * @brief The per-cell tile encoding (13-bit id + 3 flip bits) and the D4+ * orientation algebra shared by the painter and the C++ renderer.+ *+ * A stored cell is a `u16`: the low 13 bits are the 1-based tile id (0 = empty), the top+ * three are flip flags. The flags mirror Tiled's convention so `.tmj` imports and+ * editor-authored tiles render through one path. The C++ renderer+ * (`TilemapRenderPlugin`) interprets the same flags by the same {@link orientationPerm}+ * corner permutation — keep the base perms below byte-identical with the C++ side.+ */++/** Mirrors C++ `tilemap::TILE_ID_MASK` — 13 bits, max id 8191. */+export const TILE_ID_MASK = 0x1fff;+export const TILE_FLIP_H = 0x2000;+export const TILE_FLIP_V = 0x4000;+export const TILE_FLIP_D = 0x8000;+export const TILE_FLAGS_MASK = TILE_FLIP_H | TILE_FLIP_V | TILE_FLIP_D;++/** The three orientation bits a cell can carry (Tiled H/V/anti-diagonal). */+export interface TileFlags {+ flipH: boolean;+ flipV: boolean;+ flipD: boolean;+}++export const NO_FLAGS: TileFlags = { flipH: false, flipV: false, flipD: false };++/** The 1-based tile id of a raw cell (flip bits stripped); 0 = empty. */+export function tileIdOf(raw: number): number {+ return raw & TILE_ID_MASK;+}++export function tileFlagsOf(raw: number): TileFlags {+ return {+ flipH: (raw & TILE_FLIP_H) !== 0,+ flipV: (raw & TILE_FLIP_V) !== 0,+ flipD: (raw & TILE_FLIP_D) !== 0,+ };+}++/** Pack a tile id + flags into a raw cell value. `id` is masked to 13 bits. */+export function encodeTile(id: number, flags: TileFlags = NO_FLAGS): number {+ let raw = id & TILE_ID_MASK;+ if (flags.flipH) raw |= TILE_FLIP_H;+ if (flags.flipV) raw |= TILE_FLIP_V;+ if (flags.flipD) raw |= TILE_FLIP_D;+ return raw;+}++/**+ * The four quad corners, indexed in the renderer's vertex order: 0=BL, 1=BR, 2=TR, 3=TL+ * (screen space, y-up). A "corner permutation" `p` means screen corner `i` samples the+ * atlas corner `p[i]`; identity `[0,1,2,3]` is the unflipped tile.+ */+type Perm = readonly [number, number, number, number];++const IDENT: Perm = [0, 1, 2, 3];+const P_H: Perm = [1, 0, 3, 2]; // mirror left/right (BL↔BR, TL↔TR)+const P_V: Perm = [3, 2, 1, 0]; // mirror top/bottom (BL↔TL, BR↔TR)+const P_D: Perm = [0, 3, 2, 1]; // anti-diagonal flip (TL↔BR), the Tiled "diagonal" bit+const P_ROT_CW: Perm = [1, 2, 3, 0]; // rotate the displayed tile 90° clockwise++/** Compose perms: `(compose(a,b))[i] = a[b[i]]` — apply `b` then `a`. */+function compose(a: Perm, b: Perm): Perm {+ return [a[b[0]], a[b[1]], a[b[2]], a[b[3]]];+}++/**+ * The atlas-corner permutation a cell's flags produce. Flags apply D first, then V, then H+ * — the order that makes (H,V,D) bijective onto the 8 D4 orientations and matches Tiled.+ */+export function orientationPerm(flags: TileFlags): Perm {+ let p: Perm = IDENT;+ if (flags.flipD) p = compose(P_D, p);+ if (flags.flipV) p = compose(P_V, p);+ if (flags.flipH) p = compose(P_H, p);+ return p;+}++// Reverse map: orientation perm → the flags that produce it (built from the 8 combos).+const PERM_TO_FLAGS = new Map<string, TileFlags>();+for (let bits = 0; bits < 8; bits++) {+ const flags: TileFlags = {+ flipH: (bits & 1) !== 0,+ flipV: (bits & 2) !== 0,+ flipD: (bits & 4) !== 0,+ };+ PERM_TO_FLAGS.set(orientationPerm(flags).join(','), flags);+}++function flagsForPerm(p: Perm): TileFlags {+ return PERM_TO_FLAGS.get(p.join(',')) ?? NO_FLAGS;+}++/** Apply a screen-space transform (pre-composed) to a cell's flags, returning new flags. */+function transformFlags(screen: Perm, flags: TileFlags): TileFlags {+ return flagsForPerm(compose(screen, orientationPerm(flags)));+}++export function flipFlagsH(flags: TileFlags): TileFlags {+ return transformFlags(P_H, flags);+}+export function flipFlagsV(flags: TileFlags): TileFlags {+ return transformFlags(P_V, flags);+}+export function rotateFlagsCW(flags: TileFlags): TileFlags {+ return transformFlags(P_ROT_CW, flags);+}diff --git a/sdk/src/tilemap/tileStamp.ts b/sdk/src/tilemap/tileStamp.tsnew file mode 100644index 000000000..163bad81a--- /dev/null+++ b/sdk/src/tilemap/tileStamp.ts@@ -0,0 +1,76 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file tileStamp.ts+ * @brief The painter's brush: a rectangular pattern of raw cells (a "stamp"), the+ * unit that the palette selects, the brush paints, and autotile/eyedropper+ * produce. Replaces the old single-tile-id brush so multi-tile selection,+ * flip and rotate all flow through one model.+ *+ * Each cell is a raw `u16` (see {@link encodeTile}); 0 = empty (paints nothing — the+ * stamp is sparse, so an irregular eyedropper/selection leaves gaps untouched). Flip and+ * rotate transform both the cell grid and every non-empty cell's own orientation flags.+ */++import {+ encodeTile, tileIdOf, tileFlagsOf,+ flipFlagsH, flipFlagsV, rotateFlagsCW,+ type TileFlags,+} from './tileBits';++/** A w×h block of raw cells, row-major. `cells.length === w * h`. */+export interface TileStamp {+ w: number;+ h: number;+ cells: number[];+}++/** A 1×1 stamp of one raw cell. */+export function singleStamp(raw: number): TileStamp {+ return { w: 1, h: 1, cells: [raw] };+}++/** Whether the stamp paints nothing (all cells empty) — treated as a no-op brush. */+export function isEmptyStamp(s: TileStamp): boolean {+ return s.w <= 0 || s.h <= 0 || s.cells.every((c) => tileIdOf(c) === 0);+}++function mapCell(raw: number, op: (f: TileFlags) => TileFlags): number {+ const id = tileIdOf(raw);+ return id === 0 ? 0 : encodeTile(id, op(tileFlagsOf(raw)));+}++export function flipStampH(s: TileStamp): TileStamp {+ const cells = new Array<number>(s.cells.length);+ for (let y = 0; y < s.h; y++) {+ for (let x = 0; x < s.w; x++) {+ cells[y * s.w + (s.w - 1 - x)] = mapCell(s.cells[y * s.w + x], flipFlagsH);+ }+ }+ return { w: s.w, h: s.h, cells };+}++export function flipStampV(s: TileStamp): TileStamp {+ const cells = new Array<number>(s.cells.length);+ for (let y = 0; y < s.h; y++) {+ for (let x = 0; x < s.w; x++) {+ cells[(s.h - 1 - y) * s.w + x] = mapCell(s.cells[y * s.w + x], flipFlagsV);+ }+ }+ return { w: s.w, h: s.h, cells };+}++/** Rotate the stamp 90° clockwise (w×h → h×w). */+export function rotateStampCW(s: TileStamp): TileStamp {+ const nw = s.h;+ const nh = s.w;+ const cells = new Array<number>(s.cells.length);+ for (let y = 0; y < s.h; y++) {+ for (let x = 0; x < s.w; x++) {+ const nx = s.h - 1 - y;+ const ny = x;+ cells[ny * nw + nx] = mapCell(s.cells[y * s.w + x], rotateFlagsCW);+ }+ }+ return { w: nw, h: nh, cells };+}diff --git a/sdk/src/tilemap/tilesetAsset.ts b/sdk/src/tilemap/tilesetAsset.tsindex 50a390f3b..3b27b89a9 100644--- a/sdk/src/tilemap/tilesetAsset.ts+++ b/sdk/src/tilemap/tilesetAsset.ts@@ -33,11 +33,33 @@ export interface TilesetAnimFrame {durationMs: number;}+/**+ * How a terrain's tiles peer with their neighbours. `edge` = 4-bit N/E/S/W matching+ * (16-tile sets, good for ground/walls); `corner` = the 8-bit "corners and sides" blob+ * (up to 47 tiles, smooth blobby terrain). See `autotile.ts` for the resolver.+ */+export type TerrainMode = 'edge' | 'corner';++/** A named terrain (autotile rule set) in a tileset; tiles join it via {@link TilesetTileTerrain}. */+export interface TilesetTerrain {+ name: string;+ mode: TerrainMode;+ /** Authoring tint for the terrain (CSS color); cosmetic. */+ color?: string;+}++/** A tile's membership in a terrain: which set, and its peering bitmask (see `autotile.ts`). */+export interface TilesetTileTerrain {+ set: number;+ mask: number;+}+/** Per-tile metadata. Sparse — only tiles that carry any of these appear in the map. */export interface TilesetTile {collision?: TilesetCollision;properties?: Record<string, string>;animation?: TilesetAnimFrame[];+ terrain?: TilesetTileTerrain;}/** A reusable tileset palette asset (`.estileset`). */@@ -57,6 +79,8 @@ export interface TilesetAsset {tileCount?: number;/** Per-tile metadata keyed by tile id (1-based; id 0 = empty). */tiles: Record<number, TilesetTile>;+ /** Terrain (autotile) rule sets; a tile joins one via its `terrain.set` index. */+ terrains?: TilesetTerrain[];}function posInt(v: unknown, fallback: number): number {@@ -102,8 +126,22 @@ export function parseTileset(raw: any): TilesetAsset {.map((f: any) => ({ tile: f.tile, durationMs: nonNeg(f.durationMs, 100) }));if (frames.length > 0) tile.animation = frames;}- if (tile.collision || tile.properties || tile.animation) tiles[id] = tile;+ if (t.terrain && typeof t.terrain === 'object'+ && Number.isInteger(t.terrain.set) && t.terrain.set >= 0+ && Number.isInteger(t.terrain.mask) && t.terrain.mask >= 0) {+ tile.terrain = { set: t.terrain.set, mask: t.terrain.mask };+ }+ if (tile.collision || tile.properties || tile.animation || tile.terrain) tiles[id] = tile;}+ const terrains: TilesetTerrain[] = Array.isArray(raw?.terrains)+ ? raw.terrains+ .filter((t: any) => t && typeof t.name === 'string')+ .map((t: any): TilesetTerrain => ({+ name: t.name,+ mode: t.mode === 'corner' ? 'corner' : 'edge',+ ...(typeof t.color === 'string' ? { color: t.color } : {}),+ }))+ : [];return {version: typeof raw?.version === 'string' ? raw.version : TILESET_FORMAT_VERSION,texture: typeof raw?.texture === 'string' ? raw.texture : '',@@ -114,6 +152,7 @@ export function parseTileset(raw: any): TilesetAsset {spacing: nonNeg(raw?.spacing, 0),tileCount: Number.isInteger(raw?.tileCount) ? raw.tileCount : undefined,tiles,+ ...(terrains.length > 0 ? { terrains } : {}),};}@@ -132,6 +171,7 @@ export function serializeTileset(asset: TilesetAsset): Record<string, unknown> {tiles,};if (asset.tileCount !== undefined) out.tileCount = asset.tileCount;+ if (asset.terrains && asset.terrains.length > 0) out.terrains = asset.terrains;return out;}diff --git a/sdk/tests/autotile.test.ts b/sdk/tests/autotile.test.tsnew file mode 100644index 000000000..d21fa221d--- /dev/null+++ b/sdk/tests/autotile.test.ts@@ -0,0 +1,106 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+import { describe, it, expect } from 'vitest';+import { parseTileset, serializeTileset, type TilesetAsset } from '../src/tilemap/tilesetAsset';+import {+ TB_N, TB_E, TB_S, TB_W, TB_NE, TB_SE, TB_SW, TB_NW, TERRAIN_NEIGHBORS,+ normalizeCornerMask, buildTerrainIndices, resolveAutotile,+} from '../src/tilemap/autotile';++describe('tileset terrain round-trip', () => {+ it('parses and serializes terrains + per-tile terrain', () => {+ const raw = {+ version: '1', texture: '@uuid:x', tileWidth: 16, tileHeight: 16, columns: 4,+ margin: 0, spacing: 0,+ terrains: [{ name: 'Grass', mode: 'corner', color: '#3a3' }, { name: 'Dirt', mode: 'edge' }],+ tiles: {+ 5: { terrain: { set: 0, mask: TB_N | TB_E } },+ 6: { collision: { type: 'box' }, terrain: { set: 1, mask: TB_S } },+ },+ };+ const a = parseTileset(raw);+ expect(a.terrains).toHaveLength(2);+ expect(a.terrains?.[0]).toEqual({ name: 'Grass', mode: 'corner', color: '#3a3' });+ expect(a.terrains?.[1].mode).toBe('edge');+ expect(a.tiles[5].terrain).toEqual({ set: 0, mask: TB_N | TB_E });+ expect(a.tiles[6].terrain).toEqual({ set: 1, mask: TB_S });+ // round-trips+ expect(parseTileset(serializeTileset(a))).toEqual(a);+ });++ it('drops invalid terrain entries and unknown modes default to edge', () => {+ const a = parseTileset({+ tiles: { 1: { terrain: { set: -1, mask: 2 } }, 2: { terrain: { set: 0, mask: 1 } } },+ terrains: [{ name: 'X', mode: 'weird' }, { notName: true }],+ });+ expect(a.tiles[1]?.terrain).toBeUndefined(); // set < 0 rejected+ expect(a.tiles[2]?.terrain).toEqual({ set: 0, mask: 1 });+ expect(a.terrains).toHaveLength(1);+ expect(a.terrains?.[0]).toEqual({ name: 'X', mode: 'edge' });+ });+});++describe('corner (blob) mask normalization', () => {+ it('keeps a corner only when both adjacent sides peer', () => {+ // NE present but missing N → NE dropped.+ expect(normalizeCornerMask(TB_NE | TB_E)).toBe(TB_E);+ // NE present with both N and E → kept.+ expect(normalizeCornerMask(TB_NE | TB_N | TB_E)).toBe(TB_NE | TB_N | TB_E);+ // all sides + all corners → full mask kept.+ const full = TB_N | TB_E | TB_S | TB_W | TB_NE | TB_SE | TB_SW | TB_NW;+ expect(normalizeCornerMask(full)).toBe(full);+ });+});++function neighborsFromMask(mask: number): boolean[] {+ return TERRAIN_NEIGHBORS.map((n) => (mask & n.bit) !== 0);+}++describe('resolveAutotile', () => {+ it('edge mode: each of the 16 side combos resolves to its own tile', () => {+ const tiles: TilesetAsset['tiles'] = {};+ for (let m = 0; m < 16; m++) tiles[m + 1] = { terrain: { set: 0, mask: m } };+ const asset = parseTileset({+ tiles, terrains: [{ name: 'G', mode: 'edge' }],+ });+ const idx = buildTerrainIndices(asset).sets.get(0)!;+ for (let m = 0; m < 16; m++) {+ expect(resolveAutotile(idx, neighborsFromMask(m))).toBe(m + 1);+ }+ });++ it('edge mode: corner-only neighbours are ignored (masked to sides)', () => {+ const asset = parseTileset({+ tiles: { 1: { terrain: { set: 0, mask: 0 } } }, terrains: [{ name: 'G', mode: 'edge' }],+ });+ const idx = buildTerrainIndices(asset).sets.get(0)!;+ // only NE/SW peer → no side bits → resolves to the mask-0 tile.+ expect(resolveAutotile(idx, neighborsFromMask(TB_NE | TB_SW))).toBe(1);+ });++ it('falls back to the nearest mask by Hamming distance when no exact match', () => {+ const asset = parseTileset({+ tiles: {+ 1: { terrain: { set: 0, mask: 0 } },+ 2: { terrain: { set: 0, mask: TB_N | TB_E | TB_S | TB_W } },+ },+ terrains: [{ name: 'G', mode: 'edge' }],+ });+ const idx = buildTerrainIndices(asset).sets.get(0)!;+ // N|E|S (3 bits) is closer to the full 4-bit tile than to the empty tile.+ expect(resolveAutotile(idx, neighborsFromMask(TB_N | TB_E | TB_S))).toBe(2);+ // N only (1 bit) is closer to empty.+ expect(resolveAutotile(idx, neighborsFromMask(TB_N))).toBe(1);+ });++ it('reverse tile→terrain map covers every terrain tile', () => {+ const asset = parseTileset({+ tiles: { 3: { terrain: { set: 0, mask: 1 } }, 9: { terrain: { set: 1, mask: 2 } } },+ terrains: [{ name: 'A', mode: 'edge' }, { name: 'B', mode: 'edge' }],+ });+ const { tileTerrain } = buildTerrainIndices(asset);+ expect(tileTerrain.get(3)).toBe(0);+ expect(tileTerrain.get(9)).toBe(1);+ expect(tileTerrain.has(1)).toBe(false);+ });+});diff --git a/sdk/tests/tileBits.test.ts b/sdk/tests/tileBits.test.tsnew file mode 100644index 000000000..0eeee54ea--- /dev/null+++ b/sdk/tests/tileBits.test.ts@@ -0,0 +1,101 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+import { describe, it, expect } from 'vitest';+import {+ encodeTile, tileIdOf, tileFlagsOf, orientationPerm,+ flipFlagsH, flipFlagsV, rotateFlagsCW, NO_FLAGS,+ TILE_FLIP_H, TILE_FLIP_V, TILE_FLIP_D,+ type TileFlags,+} from '../src/tilemap/tileBits';+import {+ singleStamp, flipStampH, flipStampV, rotateStampCW, isEmptyStamp,+} from '../src/tilemap/tileStamp';++const ALL_FLAGS: TileFlags[] = [];+for (let b = 0; b < 8; b++) {+ ALL_FLAGS.push({ flipH: !!(b & 1), flipV: !!(b & 2), flipD: !!(b & 4) });+}++describe('tile bit encoding', () => {+ it('round-trips id + flags', () => {+ for (const f of ALL_FLAGS) {+ const raw = encodeTile(42, f);+ expect(tileIdOf(raw)).toBe(42);+ expect(tileFlagsOf(raw)).toEqual(f);+ }+ });++ it('masks the id to 13 bits and sets the right flag bits', () => {+ expect(encodeTile(1, { flipH: true, flipV: false, flipD: false })).toBe(1 | TILE_FLIP_H);+ expect(encodeTile(1, { flipH: false, flipV: true, flipD: false })).toBe(1 | TILE_FLIP_V);+ expect(encodeTile(1, { flipH: false, flipV: false, flipD: true })).toBe(1 | TILE_FLIP_D);+ expect(tileIdOf(0x9000 | 0x1234)).toBe(0x1234);+ });++ it('the 8 flag combos map to 8 distinct orientation perms (D4 bijection)', () => {+ const seen = new Set(ALL_FLAGS.map((f) => orientationPerm(f).join(',')));+ expect(seen.size).toBe(8);+ });+});++describe('D4 flag algebra', () => {+ it('flipH and flipV are involutions', () => {+ for (const f of ALL_FLAGS) {+ expect(flipFlagsH(flipFlagsH(f))).toEqual(f);+ expect(flipFlagsV(flipFlagsV(f))).toEqual(f);+ }+ });++ it('rotateCW has order 4', () => {+ for (const f of ALL_FLAGS) {+ expect(rotateFlagsCW(rotateFlagsCW(rotateFlagsCW(rotateFlagsCW(f))))).toEqual(f);+ }+ });++ it('flipH ∘ flipV == rotate 180 (two CW rotations)', () => {+ for (const f of ALL_FLAGS) {+ expect(flipFlagsH(flipFlagsV(f))).toEqual(rotateFlagsCW(rotateFlagsCW(f)));+ }+ });++ it('a plain tile gains the matching flag under a single op', () => {+ expect(flipFlagsH(NO_FLAGS)).toEqual({ flipH: true, flipV: false, flipD: false });+ expect(flipFlagsV(NO_FLAGS)).toEqual({ flipH: false, flipV: true, flipD: false });+ });+});++describe('tile stamps', () => {+ it('singleStamp wraps one raw cell', () => {+ const s = singleStamp(encodeTile(7));+ expect(s).toEqual({ w: 1, h: 1, cells: [7] });+ expect(isEmptyStamp(singleStamp(0))).toBe(true);+ expect(isEmptyStamp(s)).toBe(false);+ });++ it('flipStampH mirrors the grid and each cell', () => {+ // 2×1: [id1, id2] → [id2', id1'] with each cell flipped H.+ const s = { w: 2, h: 1, cells: [encodeTile(1), encodeTile(2)] };+ const r = flipStampH(s);+ expect(r.w).toBe(2);+ expect(r.h).toBe(1);+ expect(tileIdOf(r.cells[0])).toBe(2);+ expect(tileIdOf(r.cells[1])).toBe(1);+ expect(tileFlagsOf(r.cells[0]).flipH).toBe(true);+ });++ it('rotateStampCW transposes dims and rotates cells', () => {+ // 2×1 row → 1×2 column.+ const s = { w: 2, h: 1, cells: [encodeTile(1), encodeTile(2)] };+ const r = rotateStampCW(s);+ expect(r.w).toBe(1);+ expect(r.h).toBe(2);+ // 4× rotate restores the original.+ expect(rotateStampCW(rotateStampCW(rotateStampCW(rotateStampCW(s))))).toEqual(s);+ });++ it('empty cells stay empty through transforms', () => {+ const s = { w: 2, h: 1, cells: [0, encodeTile(5)] };+ expect(flipStampH(s).cells.filter((c) => tileIdOf(c) === 0).length).toBe(1);+ expect(rotateStampCW(s).cells.filter((c) => tileIdOf(c) === 0).length).toBe(1);+ });+});