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): corner-Wang (multi-terrain) autotiling, end to end
yhhe983cb825661
diff --git a/desktop/src/i18n/messages/tile.ts b/desktop/src/i18n/messages/tile.tsindex cd0ab3223..a948d0398 100644--- a/desktop/src/i18n/messages/tile.ts+++ b/desktop/src/i18n/messages/tile.ts@@ -164,8 +164,17 @@ export const tileMessages = defineMessages({'tile.terrain.modeAria': { en: 'Terrain mode', zh: '地形模式' },'tile.terrain.edge4': { en: 'Edge (4-bit)', zh: '边(4 位)' },'tile.terrain.cornerBlob': { en: 'Corner (blob)', zh: '角(blob)' },+ 'tile.terrain.wang': { en: 'Corner (Wang)', zh: '角(Wang)' },+ 'tile.terrain.wangShort': { en: 'Wang', zh: 'Wang' },'tile.terrain.delete': { en: 'Delete terrain', zh: '删除地形' },+ // — Tileset editor: wang (corner) terrain authoring —+ 'tile.wang.cornerTip': { en: 'Paint the active color on the {dir} corner (right-click clears)', zh: '在{dir}角绘制当前颜色(右键清除)' },+ 'tile.wang.pickColor': { en: 'Paint with "{name}"', zh: '使用「{name}」绘制' },+ 'tile.wang.recolor': { en: 'Change color', zh: '更改颜色' },+ 'tile.wang.addColor': { en: 'Add color', zh: '添加颜色' },+ 'tile.wang.removeColor': { en: 'Remove color', zh: '删除颜色' },+// — Tileset editor: animation authoring —'tile.anim.pickHint': {en: 'Click a tile in the atlas to edit its animation — animated tiles carry a ▶ mark',diff --git a/desktop/src/main.tsx b/desktop/src/main.tsxindex d7192fedf..8b57a1fd4 100644--- a/desktop/src/main.tsx+++ b/desktop/src/main.tsx@@ -50,6 +50,7 @@ import { commands } from './commands/registry';import { ENTITY_SOURCES, sourceById, createFromSource, type TileGridConfig } from './engine/entitySources';import { createTilemapFromTileset } from './tilemap/createTilemap';import { SceneCommands } from './engine/SceneCommands';+import { useTilemapPaint } from './store/tilemapPaintStore';import { ViewportController } from './engine/ViewportController';import { PerfMonitor } from './engine/PerfMonitor';import { LogStore } from './store/LogStore';@@ -141,6 +142,13 @@ if (new URLSearchParams(location.search).has('automation')) {/** Paint tiles into a TilemapLayer SOURCE entity (one undo step) — for shot tests. */paintTiles: (sourceId: number, edits: { x: number; y: number; tileId: number }[]) =>SceneCommands.paintTiles(sourceId, edits),+ /** Drive the tilemap paint store (tool / terrain set / wang color) — for shot tests. */+ setTilePaint: (patch: { tool?: unknown; terrainSet?: number; wangColor?: number }) => {+ const s = useTilemapPaint.getState();+ if (patch.tool !== undefined) s.setTool(patch.tool as never);+ if (patch.terrainSet !== undefined) s.setTerrainSet(patch.terrainSet);+ if (patch.wangColor !== undefined) s.setWangColor(patch.wangColor);+ },/** Spawn a ready-made entity through the one create pipeline (menu/DnD parity). */createEntity: async (sourceId: string, opts?: { parent?: number | null; x?: number; y?: number }) => {const source = sourceById(sourceId);diff --git a/desktop/src/panels/TilemapPainter.tsx b/desktop/src/panels/TilemapPainter.tsxindex 30075b6d2..6c0d78a73 100644--- a/desktop/src/panels/TilemapPainter.tsx+++ b/desktop/src/panels/TilemapPainter.tsx@@ -89,8 +89,8 @@ function BrushThumbnail({ stamp, atlas }: { stamp: TileStamp; atlas: AtlasInfo |export function TilemapPainter() {const {- tilesetPath, tilesets, activeTileset, stamp, tool, terrainSet,- setTilesets, setActiveTileset, setTilesetAsset, setStamp, setBrushTile, setTool, setTerrainSet,+ tilesetPath, tilesets, activeTileset, stamp, tool, terrainSet, wangColor,+ setTilesets, setActiveTileset, setTilesetAsset, setStamp, setBrushTile, setTool, setTerrainSet, setWangColor,setActiveAtlas, flipH, flipV, rotateCW, randomBrush, toggleRandomBrush,} = useTilemapPaint();const win = usePanelWindow();@@ -583,16 +583,37 @@ export function TilemapPainter() {{(asset?.terrains ?? []).length === 0 ? (<div className="tp-warn">{t('tile.noTerrains')}</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>+ (asset?.terrains ?? []).map((ter, i) => (+ ter.mode === 'wang' ? (+ // A wang set paints by COLOR: one swatch button per color in the set.+ <span key={i} className="tp-wgroup">+ <span className="tp-wglabel">{ter.name}</span>+ <span className="tp-wcrow">+ {(ter.colors ?? []).map((c, ci) => (+ <button+ key={ci}+ type="button"+ className={'tp-wcbtn' + (i === terrainSet && ci + 1 === wangColor ? ' is-active' : '')}+ title={c.name}+ onClick={() => { setTerrainSet(i); setWangColor(ci + 1); }}+ >+ <span className="tp-tswatch" style={{ background: c.color }} />+ {c.name}+ </button>+ ))}+ </span>+ </span>+ ) : (+ <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] }} />+ {ter.name}+ </button>+ ))))}</div>diff --git a/desktop/src/panels/TilesetEditor.tsx b/desktop/src/panels/TilesetEditor.tsxindex c093dbf26..e4d073d5b 100644--- a/desktop/src/panels/TilesetEditor.tsx+++ b/desktop/src/panels/TilesetEditor.tsx@@ -48,6 +48,15 @@ const ZONES: { gx: number; gy: number; bit: number; corner: boolean; dir: string{ gx: 0, gy: 0, bit: TB_NW, corner: true, dir: t('tile.dir.northWest') },];+// Wang corner dots, placed at the cell's 4 corners. Index order matches the tile's+// `corners` array: [top-left, top-right, bottom-right, bottom-left].+const WANG_CORNERS: { i: number; gx: number; gy: number; dir: string }[] = [+ { i: 0, gx: 0, gy: 0, dir: t('tile.dir.northWest') },+ { i: 1, gx: 1, gy: 0, dir: t('tile.dir.northEast') },+ { i: 2, gx: 1, gy: 1, dir: t('tile.dir.southEast') },+ { i: 3, gx: 0, gy: 1, dir: t('tile.dir.southWest') },+];+/** A focused per-tile collision-polygon editor: a magnified tile + click-to-add /* click-a-point-to-remove vertices, committed live (≥3 points) as undo steps. */function PolygonEditor(props: {@@ -180,6 +189,8 @@ export function TilesetEditor() {const [restitutionStr, setRestitutionStr] = useState('');const [densityStr, setDensityStr] = useState('');const [activeSet, setActiveSet] = useState(0);+ // The wang color being painted onto tile corners (1-based into the set's colors).+ const [activeColor, setActiveColor] = useState(1);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);@@ -275,6 +286,9 @@ export function TilesetEditor() {if (tileTerrain(id)) TilesetCommands.setTileTerrain(id, null, 0);else TilesetCommands.setTileTerrain(id, activeSet, 0);};+ // Wang authoring: assign the active color to one of a tile's 4 corners (right-click clears).+ const setCorner = (id: number, corner: number, color: number) =>+ TilesetCommands.setTileWangCorner(id, activeSet, corner, color);// ── animation authoring ──const animFrames: TilesetAnimFrame[] = animTile != null ? asset.tiles[animTile]?.animation ?? [] : [];@@ -396,10 +410,11 @@ export function TilesetEditor() {/>,);} else {+ const isWang = terrain?.mode === 'wang';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;+ if (tt && !isWang) (cellStyle as Record<string, string | number>)['--tcolor'] = terrainColor;cells.push(<divkey={id}@@ -409,25 +424,48 @@ export function TilesetEditor() {onPointerEnter={() => setHovered(id)}onPointerLeave={() => setHovered((cur) => (cur === id ? null : cur))}>- <button- type="button" className="ts-zone ts-zone-c"- title={t('tile.zone.member')}- onClick={() => toggleMember(id)}- />- {showZones && terrain && ZONES.filter((z) => terrain.mode === 'corner' || !z.corner).map((z) => {- const on = ((tt?.mask ?? 0) & z.bit) !== 0;- return (+ {isWang ? (+ // A colored dot at each of the tile's 4 corners — click paints the active+ // color, right-click clears. The dots ARE the "circle in the corner" UI.+ (showZones || tt) && terrain && WANG_CORNERS.map((c) => {+ const cv = tt?.corners?.[c.i] ?? 0;+ const col = cv > 0 ? terrain.colors?.[cv - 1]?.color : undefined;+ return (+ <button+ key={c.i}+ type="button"+ className={'ts-wcorner' + (cv > 0 ? ' is-on' : '')}+ style={{ left: `${c.gx * 100}%`, top: `${c.gy * 100}%`, ...(col ? { background: col } : {}) }}+ aria-label={t('tile.zone.aria', { dir: c.dir })}+ title={t('tile.wang.cornerTip', { dir: c.dir })}+ onClick={() => setCorner(id, c.i, activeColor)}+ onContextMenu={(e) => { e.preventDefault(); setCorner(id, c.i, 0); }}+ />+ );+ })+ ) : (+ <><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}%` }}- aria-label={t('tile.zone.aria', { dir: z.dir })}- title={t('tile.zone.peerTip', { dir: z.dir })}- onClick={() => toggleBit(id, z.bit)}+ type="button" className="ts-zone ts-zone-c"+ title={t('tile.zone.member')}+ 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}%` }}+ aria-label={t('tile.zone.aria', { dir: z.dir })}+ title={t('tile.zone.peerTip', { dir: z.dir })}+ onClick={() => toggleBit(id, z.bit)}+ />+ );+ })}+ </>+ )}</div>,);}@@ -544,7 +582,7 @@ export function TilesetEditor() {><span className="ts-tswatch" style={{ background: TERRAIN_COLORS[i % TERRAIN_COLORS.length] }} />{ter.name}- <span className="ts-tmode">{ter.mode === 'corner' ? t('tile.terrain.cornerShort') : t('tile.terrain.edgeShort')}</span>+ <span className="ts-tmode">{ter.mode === 'corner' ? t('tile.terrain.cornerShort') : ter.mode === 'wang' ? t('tile.terrain.wangShort') : t('tile.terrain.edgeShort')}</span></button>))}<button type="button" className="ts-terrain ts-add" title={t('tile.terrain.new')}@@ -563,6 +601,7 @@ export function TilesetEditor() {options={[{ value: 'edge', label: t('tile.terrain.edge4') },{ value: 'corner', label: t('tile.terrain.cornerBlob') },+ { value: 'wang', label: t('tile.terrain.wang') },]}onChange={(v) => TilesetCommands.updateTerrain(activeSet, { mode: v })}/>@@ -572,6 +611,42 @@ export function TilesetEditor() {</button></div>)}+ {terrain?.mode === 'wang' && (+ // The wang color palette: pick the active color, rename/recolor, add/remove.+ // Then click tile corners in the atlas to paint that color.+ <div className="ts-wcolors">+ {(terrain.colors ?? []).map((c, i) => (+ <span key={i} className={'ts-wcolor' + (activeColor === i + 1 ? ' is-active' : '')}>+ <button+ type="button" className="ts-wswatch" style={{ background: c.color }}+ title={t('tile.wang.pickColor', { name: c.name })} onClick={() => setActiveColor(i + 1)}+ />+ <input+ className="ts-wcname" value={c.name}+ onChange={(e) => TilesetCommands.updateWangColor(activeSet, i, { name: e.target.value })}+ />+ <input+ className="ts-wcpick" type="color" value={c.color} title={t('tile.wang.recolor')}+ onChange={(e) => TilesetCommands.updateWangColor(activeSet, i, { color: e.target.value })}+ />+ {(terrain.colors?.length ?? 0) > 1 && (+ <button+ type="button" className="ts-wcx" title={t('tile.wang.removeColor')}+ onClick={() => { TilesetCommands.removeWangColor(activeSet, i); setActiveColor(1); }}+ >+ <X size={11} />+ </button>+ )}+ </span>+ ))}+ <button+ type="button" className="ts-wcadd" title={t('tile.wang.addColor')}+ onClick={() => { TilesetCommands.addWangColor(activeSet); setActiveColor((terrain.colors?.length ?? 0) + 1); }}+ >+ <Plus size={12} />+ </button>+ </div>+ )}</div>)}diff --git a/desktop/src/store/tilemapPaintStore.ts b/desktop/src/store/tilemapPaintStore.tsindex 1a188bda0..e66ee3c0e 100644--- a/desktop/src/store/tilemapPaintStore.ts+++ b/desktop/src/store/tilemapPaintStore.ts@@ -60,6 +60,8 @@ interface TilemapPaintState {stamp: TileStamp;/** The active terrain set index (for the terrain tool). */terrainSet: number;+ /** The active wang color (1-based) painted when the active terrain set is a wang set. */+ wangColor: number;/** The select tool's current marquee (tile coords), or null. */selection: TileRect | null;/** The copy/cut buffer — a stamp lifted from a selection; pasted via the brush. */@@ -83,6 +85,7 @@ interface TilemapPaintState {/** Set a 1×1 brush of one tile id (palette single-click; loses any flip flags). */setBrushTile(tileId: number): void;setTerrainSet(set: number): void;+ setWangColor(color: number): void;setActiveAtlas(atlas: AtlasInfo | null): void;flipH(): void;flipV(): void;@@ -98,6 +101,7 @@ export const useTilemapPaint = create<TilemapPaintState>((set) => ({tilesetAsset: null,stamp: singleStamp(encodeTile(1)),terrainSet: 0,+ wangColor: 1,selection: null,clipboard: null,tool: null,@@ -123,6 +127,7 @@ export const useTilemapPaint = create<TilemapPaintState>((set) => ({setClipboard: (clipboard) => set({ clipboard }),setBrushTile: (tileId) => set({ stamp: singleStamp(encodeTile(tileId)) }),setTerrainSet: (terrainSet) => set({ terrainSet }),+ setWangColor: (wangColor) => set({ wangColor }),setActiveAtlas: (activeAtlas) => set({ activeAtlas }),flipH: () => set((s) => ({ stamp: flipStampH(s.stamp) })),flipV: () => set((s) => ({ stamp: flipStampV(s.stamp) })),diff --git a/desktop/src/theme/tilemap.css b/desktop/src/theme/tilemap.cssindex 830a4e5e8..94ed42328 100644--- a/desktop/src/theme/tilemap.css+++ b/desktop/src/theme/tilemap.css@@ -193,7 +193,28 @@}.tp-terrain:not(.is-active):hover { border-color: var(--line-strong); color: var(--text); }.tp-terrain.is-active { border-color: var(--star); color: var(--text); }-.tp-tswatch { width: 12px; height: 12px; border-radius: var(--r-xs); display: inline-block; }+.tp-tswatch { width: 12px; height: 12px; border-radius: var(--r-xs); display: inline-block; flex: 0 0 auto; }++/* Wang (corner) terrain: paint by COLOR, so the terrain list shows a labeled group of+ color-swatch buttons (one per color in the set) instead of a single terrain button. */+.tp-wgroup { display: flex; flex-direction: column; gap: 4px; }+.tp-wglabel { font-size: var(--fs-2xs); font-weight: 600; color: var(--text-mute); text-transform: uppercase; letter-spacing: 0.04em; }+.tp-wcrow { display: flex; flex-wrap: wrap; gap: 4px; }+.tp-wcbtn {+ display: inline-flex;+ align-items: center;+ gap: 6px;+ background: var(--srf-3);+ border: 1px solid var(--line);+ border-radius: var(--r-sm);+ color: var(--text-dim);+ padding: 4px 9px;+ cursor: pointer;+ font: inherit;+ text-align: left;+}+.tp-wcbtn:not(.is-active):hover { border-color: var(--line-strong); color: var(--text); }+.tp-wcbtn.is-active { border-color: var(--star); color: var(--text); box-shadow: 0 0 0 1px var(--star); }/* Multi-tileset tab bar — switch which of the layer's tilesets the palette paints from. */.tp-tilesets {diff --git a/desktop/src/theme/tileset.css b/desktop/src/theme/tileset.cssindex 9f82de3f5..4635678aa 100644--- a/desktop/src/theme/tileset.css+++ b/desktop/src/theme/tileset.css@@ -253,6 +253,91 @@.ts-zone-c { left: 33.34%; top: 33.34%; }.ts-zone-c:hover { background: rgba(255, 255, 255, 0.1); }+/* Wang (corner) authoring: a colored dot at each of a tile's 4 corners — the "circle in+ the corner" UI. Empty = faint ring; assigned = filled with the terrain color (inline). */+.ts-wcorner {+ position: absolute;+ width: 11px;+ height: 11px;+ margin: 0;+ padding: 0;+ transform: translate(-50%, -50%);+ border-radius: 50%;+ border: 1px solid rgba(255, 255, 255, 0.55);+ background: rgba(18, 19, 24, 0.5);+ box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.5);+ cursor: pointer;+}+.ts-wcorner.is-on { border-color: rgba(255, 255, 255, 0.9); }+.ts-wcorner:hover { border-color: var(--star); transform: translate(-50%, -50%) scale(1.15); }++/* Wang color palette (below the terrain editor row): swatch · name · picker · remove. */+.ts-wcolors {+ width: 100%;+ display: flex;+ flex-wrap: wrap;+ align-items: center;+ gap: 6px;+ margin-top: 6px;+ padding-top: 8px;+ border-top: 1px solid var(--line);+}+.ts-wcolor {+ display: inline-flex;+ align-items: center;+ gap: 3px;+ background: var(--srf-3);+ border: 1px solid var(--line);+ border-radius: var(--r-sm);+ padding: 2px 4px 2px 3px;+}+.ts-wcolor.is-active { border-color: var(--star); box-shadow: 0 0 0 1px var(--star); }+.ts-wswatch {+ width: 18px;+ height: 18px;+ border-radius: var(--r-xs);+ border: 1px solid rgba(0, 0, 0, 0.4);+ padding: 0;+ cursor: pointer;+}+.ts-wcname {+ width: 62px;+ background: none;+ border: none;+ color: var(--text-dim);+ font: inherit;+ font-size: var(--fs-xs);+ padding: 2px;+ outline: none;+}+.ts-wcname:focus { color: var(--text); }+.ts-wcpick { width: 20px; height: 20px; padding: 0; border: none; background: none; cursor: pointer; }+.ts-wcx {+ display: inline-flex;+ align-items: center;+ justify-content: center;+ width: 16px;+ height: 16px;+ background: none;+ border: none;+ color: var(--text-faint);+ cursor: pointer;+}+.ts-wcx:hover { color: var(--error); }+.ts-wcadd {+ display: inline-flex;+ align-items: center;+ gap: 3px;+ background: var(--srf-3);+ border: 1px dashed var(--line);+ border-radius: var(--r-sm);+ color: var(--text-dim);+ padding: 4px 8px;+ cursor: pointer;+ font: inherit;+}+.ts-wcadd:hover { color: var(--text); border-color: var(--star); }+/* Polygon-collision cell marker + the focused polygon editor overlay */.ts-pcell.is-poly { background: color-mix(in srgb, var(--gizmo-tile) 22%, transparent); border-color: color-mix(in srgb, var(--gizmo-tile) 85%, transparent); }.ts-pcell:hover { border-color: var(--star); background: var(--star-dim); }diff --git a/desktop/src/tileset/TilesetCommands.ts b/desktop/src/tileset/TilesetCommands.tsindex 2e14cd7f4..51f0ba4ba 100644--- a/desktop/src/tileset/TilesetCommands.ts+++ b/desktop/src/tileset/TilesetCommands.ts@@ -8,7 +8,11 @@*/import { serializeTileset } from 'esengine';-import type { TilesetAsset, TilesetTerrain, TerrainMode, TilesetAnimFrame } from 'esengine';+import type { TilesetAsset, TilesetTerrain, TerrainColor, TerrainMode, TilesetAnimFrame } from 'esengine';++// A default palette for fresh wang colors (cycled as colors are added). Cosmetic — the+// user recolors from the picker; distinct enough that a new color reads as new.+const WANG_PALETTE = ['#5a9e3f', '#3a7ec8', '#d9c48a', '#8a8f96', '#8a6a44', '#b4536b', '#5bc0be', '#e0a458'];import { TilesetDocument } from './TilesetDocument';import { Toasts } from '@/store/Toasts';import { t } from '@/i18n';@@ -158,11 +162,13 @@ export const TilesetCommands = {});},- /** Add a terrain (autotile) set; returns the new set's index. */+ /** Add a terrain (autotile) set. A `wang` set is seeded with one corner color. */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 });+ const t: TilesetTerrain = { name: name || `Terrain ${terrains.length + 1}`, mode };+ if (mode === 'wang') t.colors = [{ name: 'Color 1', color: WANG_PALETTE[0] }];+ terrains.push(t);});},@@ -172,11 +178,72 @@ export const TilesetCommands = {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 (patch.mode === 'edge' || patch.mode === 'corner' || patch.mode === 'wang') {+ t.mode = patch.mode;+ if (patch.mode === 'wang' && (!t.colors || t.colors.length === 0)) {+ t.colors = [{ name: 'Color 1', color: WANG_PALETTE[0] }];+ }+ }if (typeof patch.color === 'string') t.color = patch.color;});},+ /** Append a corner color to a `wang` set (cycles the default palette). */+ addWangColor(set: number): void {+ TilesetDocument.edit('Add Terrain Color', (a) => {+ const ter = a.terrains?.[set];+ if (!ter || ter.mode !== 'wang') return;+ const colors = ter.colors ?? (ter.colors = []);+ colors.push({ name: `Color ${colors.length + 1}`, color: WANG_PALETTE[colors.length % WANG_PALETTE.length] });+ });+ },++ /** Edit a wang color's name / CSS color. */+ updateWangColor(set: number, i: number, patch: Partial<TerrainColor>): void {+ TilesetDocument.edit('Edit Terrain Color', (a) => {+ const c = a.terrains?.[set]?.colors?.[i];+ if (!c) return;+ if (typeof patch.name === 'string') c.name = patch.name;+ if (typeof patch.color === 'string') c.color = patch.color;+ });+ },++ /** Remove a wang color, reindexing tiles' corners (its value → 0, higher values −1). */+ removeWangColor(set: number, i: number): void {+ TilesetDocument.edit('Remove Terrain Color', (a) => {+ const ter = a.terrains?.[set];+ if (!ter?.colors || i < 0 || i >= ter.colors.length) return;+ ter.colors.splice(i, 1);+ const removed = i + 1; // corners are 1-based (0 = none)+ for (const key of Object.keys(a.tiles)) {+ const id = Number(key);+ const tt = a.tiles[id].terrain;+ if (!tt || tt.set !== set || !tt.corners) continue;+ tt.corners = tt.corners.map((c) => (c === removed ? 0 : c > removed ? c - 1 : c));+ if (tt.corners.every((c) => c === 0)) { delete a.tiles[id].terrain; pruneEmpty(a, id); }+ }+ });+ },++ /**+ * Assign one corner of a tile's wang membership (corner 0-3 = TL/TR/BR/BL, color 0 = none)+ * as ONE undo step. Clearing every corner drops the membership.+ */+ setTileWangCorner(id: number, set: number, corner: number, color: number): void {+ if (id <= 0 || corner < 0 || corner > 3) return;+ TilesetDocument.edit('Edit Tile Corner', (a) => {+ const existing = a.tiles[id]?.terrain;+ const corners = existing && existing.set === set && existing.corners+ ? [...existing.corners] : [0, 0, 0, 0];+ corners[corner] = color & 0xff;+ if (corners.every((c) => c === 0)) {+ if (a.tiles[id]?.terrain) { delete a.tiles[id].terrain; pruneEmpty(a, id); }+ return;+ }+ a.tiles[id] = { ...(a.tiles[id] ?? {}), terrain: { set, corners } };+ });+ },+/** Remove a terrain set, dropping its tiles' membership and reindexing higher sets. */removeTerrain(set: number): void {TilesetDocument.edit('Remove Terrain', (a) => {diff --git a/desktop/src/tools/tileTools.ts b/desktop/src/tools/tileTools.tsindex c2a8b3ebc..08e5372fb 100644--- a/desktop/src/tools/tileTools.ts+++ b/desktop/src/tools/tileTools.ts@@ -13,6 +13,7 @@import {TilemapAPI, tileIdOf, encodeTile, singleStamp, type TileStamp,buildTerrainIndices, resolveAutotile, TERRAIN_NEIGHBORS, type TerrainIndices,+ buildWangIndices, resolveWang, type WangIndex, type TilesetAsset,} from 'esengine';import { ViewportController } from '@/engine/ViewportController';import { SceneCommands, type TilePaint } from '@/engine/SceneCommands';@@ -282,20 +283,39 @@ const eraseTool = makeStrokeTool<number>({end: () => SceneCommands.endTilePaint(),});-// ── Terrain (autotile) brush ─────────────────────────────────────────────────-interface TerrainCtx {+// ── Terrain brush ────────────────────────────────────────────────────────────+// Two terrain models share one brush. PEERING (edge / corner blob) joins a cell to a+// single terrain and re-tiles by neighbour matching. WANG (corner) paints a COLOR onto the+// four corners around the cursor and re-tiles the affected cells by corner match — so one+// set blends many terrains on a half-cell corner grid. The active set's `mode` picks which.+// `base` = firstId − 1: cells store GLOBAL gids but the resolvers key by tileset-LOCAL id.++interface PeerCtx {+ kind: 'peer';sourceId: number;rt: number;set: number;indices: TerrainIndices;assigned: Map<string, number>;- // firstId − 1 of the active tileset. buildTerrainIndices keys by tileset-LOCAL id,- // but cells store GLOBAL gids, so read a cell as gid − base and write local + base- // (base is 0 for a single-tileset layer, so this is a no-op there).base: number;}+interface WangCtx {+ kind: 'wang';+ sourceId: number;+ rt: number;+ set: number;+ /** The wang color being painted (1-based). */+ color: number;+ index: WangIndex;+ base: number;+ asset: TilesetAsset;+ /** Stroke-transient corner grid: vertex key "vx,vy" → color. */+ corners: Map<string, number>;+}+type TerrainStroke = PeerCtx | WangCtx;-function terrainAt(s: TerrainCtx, x: number, y: number): number | null {+// — peering —+function terrainAt(s: PeerCtx, x: number, y: number): number | null {const key = `${x},${y}`;if (s.assigned.has(key)) return s.assigned.get(key)!;const gid = tileIdOf(TilemapAPI.getTile(s.rt, x, y));@@ -303,7 +323,7 @@ function terrainAt(s: TerrainCtx, x: number, y: number): number | null {return s.indices.tileTerrain.get(gid - s.base) ?? null;}-function recomputeTerrain(s: TerrainCtx, x: number, y: number): void {+function recomputeTerrain(s: PeerCtx, x: number, y: number): void {const set = terrainAt(s, x, y);if (set == null) return;const index = s.indices.sets.get(set);@@ -314,26 +334,83 @@ function recomputeTerrain(s: TerrainCtx, x: number, y: number): void {}/** Join (x,y) to the active terrain, then re-resolve it and its 8 neighbours. */-function stampTerrain(s: TerrainCtx, x: number, y: number): void {+function stampTerrain(s: PeerCtx, x: number, y: number): void {s.assigned.set(`${x},${y}`, s.set);recomputeTerrain(s, x, y);for (const n of TERRAIN_NEIGHBORS) recomputeTerrain(s, x + n.dx, y + n.dy);}-const terrainTool = makeStrokeTool<TerrainCtx>({+// — wang (corner) —+/** The wang corner colors of the tile at cell (gid), or null if it's not this set's wang tile. */+function wangTileCorners(asset: TilesetAsset, set: number, base: number, gid: number): number[] | null {+ if (gid <= 0) return null;+ const t = asset.tiles[gid - base]?.terrain;+ return t && t.set === set && t.corners ? t.corners : null;+}++/** The color at corner-grid vertex (vx,vy): the stroke's painted value, else derived from+ * whichever placed tile owns that vertex (probing the 4 cells around it). */+function wangVertex(s: WangCtx, vx: number, vy: number): number {+ const painted = s.corners.get(`${vx},${vy}`);+ if (painted !== undefined) return painted;+ // Each vertex is the TL of cell (vx,vy), TR of (vx−1,vy), BL of (vx,vy−1), BR of (vx−1,vy−1).+ const probes: [number, number, number][] = [[vx, vy, 0], [vx - 1, vy, 1], [vx, vy - 1, 3], [vx - 1, vy - 1, 2]];+ for (const [cx, cy, ci] of probes) {+ const c = wangTileCorners(s.asset, s.set, s.base, tileIdOf(TilemapAPI.getTile(s.rt, cx, cy)));+ if (c) return c[ci] ?? 0;+ }+ return 0;+}++/** Paint the active color onto (tx,ty)'s 4 corners, then re-tile the 3×3 cells they touch. */+function stampWang(s: WangCtx, tx: number, ty: number): void {+ s.corners.set(`${tx},${ty}`, s.color);+ s.corners.set(`${tx + 1},${ty}`, s.color);+ s.corners.set(`${tx + 1},${ty + 1}`, s.color);+ s.corners.set(`${tx},${ty + 1}`, s.color);+ // Resolve all affected cells from the (post-paint) corner grid FIRST, then apply — so the+ // nine resolves don't see each other's mid-pass tile writes.+ const edits: [number, number, number][] = [];+ for (let dy = -1; dy <= 1; dy++) {+ for (let dx = -1; dx <= 1; dx++) {+ const x = tx + dx;+ const y = ty + dy;+ const corners = [wangVertex(s, x, y), wangVertex(s, x + 1, y), wangVertex(s, x + 1, y + 1), wangVertex(s, x, y + 1)];+ if (corners[0] === 0 && corners[1] === 0 && corners[2] === 0 && corners[3] === 0) continue;+ const local = resolveWang(s.index, corners);+ if (local > 0) edits.push([x, y, local]);+ }+ }+ for (const [x, y, local] of edits) SceneCommands.paintTileLive(s.sourceId, x, y, encodeTile(local + s.base));+}++const terrainTool = makeStrokeTool<TerrainStroke>({id: 'tilemap.terrain',begin: (selId) => {const rt = SceneModel.runtimeFor(selId);const ps = useTilemapPaint.getState();const asset = ps.tilesetAsset;if (rt == null || !asset) return null;+ const base = (ps.tilesets[ps.activeTileset]?.firstId ?? 1) - 1;+ const terrain = asset.terrains?.[ps.terrainSet];+ if (terrain?.mode === 'wang') {+ const index = buildWangIndices(asset).sets.get(ps.terrainSet);+ if (!index) return null; // active wang set has no corner tiles yet+ SceneCommands.beginTilePaint(selId);+ return {+ kind: 'wang', sourceId: selId, rt, set: ps.terrainSet, color: ps.wangColor || 1,+ index, base, asset, corners: new Map(),+ };+ }const indices = buildTerrainIndices(asset);if (!indices.sets.has(ps.terrainSet)) return null; // active terrain has no tiles yetSceneCommands.beginTilePaint(selId);- const base = (ps.tilesets[ps.activeTileset]?.firstId ?? 1) - 1;- return { sourceId: selId, rt, set: ps.terrainSet, indices, assigned: new Map(), base };+ return { kind: 'peer', sourceId: selId, rt, set: ps.terrainSet, indices, assigned: new Map(), base };+ },+ onCell: (s, x, y) => {+ if (s.kind === 'wang') stampWang(s, x, y);+ else if (!s.assigned.has(`${x},${y}`)) stampTerrain(s, x, y);},- onCell: (s, x, y) => { if (!s.assigned.has(`${x},${y}`)) stampTerrain(s, x, y); },end: () => SceneCommands.endTilePaint(),});diff --git a/examples/tilemap-demo/README.md b/examples/tilemap-demo/README.mdindex 30011e227..e213749b5 100644--- a/examples/tilemap-demo/README.md+++ b/examples/tilemap-demo/README.md@@ -13,6 +13,18 @@ gameplay code**; the levels live entirely in the scene/assets.| `assets/scenes/iso-map.esscene` | `TilemapLayer` · **isometric** | A diamond-grid island — water border, sand beach, grass, forest, and a stone clearing. || `assets/scenes/staggered-map.esscene` | `TilemapLayer` · **staggered** | The same diamond tiles in a staggered-isometric layout, with a river winding across the patchwork. || `assets/scenes/hex-map.esscene` | `TilemapLayer` · **hexagonal** | A pointy-top hex strategy map — a lake with a sandy shore, forest, and a snow-capped mountain range. |+| `assets/scenes/wang-map.esscene` | `TilemapLayer` · **corner-Wang terrain** | A grass island → sand beach → water sea whose transitions are **auto-tiled** by a corner-Wang set — paint a terrain color and the borders blend on their own. |++## Corner-Wang terrain (auto-tiling)++`wang.estileset` carries a **corner (Wang) terrain set** with three colors — grass,+sand, water. Each tile assigns a color to its four corners (the colored dots in the+Tileset editor's Terrain mode), and the painter's **terrain brush** picks the tile+whose corners match, so painting one color **blends into its neighbours automatically**+— the classic "circle in the four corners" technique, with **many terrains in one set**.+Author your own with **Tileset → Terrain → add a set → Corner (Wang)**, add colors,+click each tile's corners, then paint with the terrain tool. (The older `Edge` /+`Corner (blob)` peering modes are still there for single-terrain autotiling.)## Orientations@@ -46,6 +58,7 @@ live collision and animation data. So:| `assets/tilesets/terrain.estileset` | The engine-native tileset: atlas grid + per-tile collision + water animation. || `assets/tilesets/iso-tiles.png` + `iso.estileset` | Six 64×32 **isometric** diamond terrain tiles (grass/water/sand/stone/dirt/forest). || `assets/tilesets/hex-tiles.png` + `hex.estileset` | Six 64×64 pointy-top **hexagon** terrain tiles (grass/water/sand/forest/mountain/snow). |+| `assets/tilesets/wang-tiles.png` + `wang.estileset` | A 45-tile **corner-Wang** terrain set — every grass/sand/water corner combination, blended by a smooth marching-squares boundary. |The platformer art is **Kenney [Pixel Platformer](https://kenney.nl/assets/pixel-platformer)(CC0)** — reuse it freely, including commercially. Seediff --git a/examples/tilemap-demo/assets/scenes/wang-map.esscene b/examples/tilemap-demo/assets/scenes/wang-map.esscenenew file mode 100644index 000000000..d77240ef7--- /dev/null+++ b/examples/tilemap-demo/assets/scenes/wang-map.esscene@@ -0,0 +1,118 @@+{+ "version": "1.0",+ "name": "Tilemap Demo",+ "entities": [+ {+ "id": 0,+ "name": "Camera",+ "parent": null,+ "children": [],+ "visible": true,+ "components": [+ {+ "type": "Transform",+ "data": {+ "position": {+ "x": 288,+ "y": -208,+ "z": 10+ }+ }+ },+ {+ "type": "Camera",+ "data": {+ "projectionType": 1,+ "orthoSize": 235,+ "isActive": true,+ "priority": 0+ }+ }+ ]+ },+ {+ "id": 1,+ "name": "Tilemap",+ "parent": null,+ "children": [],+ "components": [+ {+ "type": "Transform",+ "data": {+ "position": {+ "x": 0,+ "y": 0,+ "z": 0+ },+ "rotation": {+ "w": 1,+ "x": 0,+ "y": 0,+ "z": 0+ },+ "scale": {+ "x": 1,+ "y": 1,+ "z": 1+ },+ "worldPosition": {+ "x": 0,+ "y": 0,+ "z": 0+ },+ "worldRotation": {+ "w": 1,+ "x": 0,+ "y": 0,+ "z": 0+ },+ "worldScale": {+ "x": 1,+ "y": 1,+ "z": 1+ }+ }+ },+ {+ "type": "TilemapLayer",+ "data": {+ "cellSize": {+ "x": 32,+ "y": 32+ },+ "orientation": 0,+ "hexSideLength": 0,+ "staggerAxis": 0,+ "staggerIndex": 0,+ "originOffset": {+ "x": 0,+ "y": 0+ },+ "tileset": 0,+ "tilesetColumns": 1,+ "tilesetRows": 1,+ "renderLayer": 0,+ "tintColor": {+ "r": 1,+ "g": 1,+ "b": 1,+ "a": 1+ },+ "opacity": 1,+ "parallaxFactor": {+ "x": 1,+ "y": 1+ },+ "visible": true,+ "tilesetAssets": [+ "@uuid:85d000f8-d6c7-4840-8442-a99535375017"+ ],+ "tilesetAsset": "@uuid:85d000f8-d6c7-4840-8442-a99535375017",+ "chunks": "RVNUTQIAAAABAAAAAAAAAC0ALQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAALQAtAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAtAC0AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAC0ALQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAALQAtAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAtAC0AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAC0ALQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAALQAtAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAtAC0AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAC0ALQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAALQAtAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAtAC0AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAC0ALQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAtAC0ALQAtAC0ALQAtAC0ALQAtAC0ALQAtAC0ALQAtAC0ALQAtAC0ALQAtACsAKgAqACoAKgAsAC0ALQAtAC0ALQAtAC0ALQArACoAJgAeAB4AHgAeACIAKgAsAC0ALQAtAC0ALQArACYAHgAeAA4ADQANAA8AHgAeACIALAAtAC0ALQArACYAHgAOAA0ACQABAAEABQANAA8AHgAiACwALQAtACcAHgAeAAoAAQABAAEAAQABAAEABwAeAB4AJAAtAC0AJwAeAB4ACgABAAEAAQABAAEAAQAHAB4AHgAkAC0ALQAnAB4AHgAKAAEAAQABAAEAAQABAAcAHgAeACQALQAtACkAHwAeAAwABAACAAEAAQADAAQACAAeACAAJQAtAC0ALQApAB8AHgAeAAwABAAEAAgAHgAeACAAJQAtAC0ALQAtAC0AKQAhAB8AHgAeAB4AHgAgACEAJQAtAC0ALQAtAC0ALQAtAC0AKQAhACEAIQAhACUALQAtAC0ALQAtAC0ALQAtAC0ALQAtAC0ALQAtAC0ALQAtAC0ALQAtAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=="+ }+ }+ ],+ "visible": true+ }+ ]+}diff --git a/examples/tilemap-demo/assets/scenes/wang-map.esscene.meta b/examples/tilemap-demo/assets/scenes/wang-map.esscene.metanew file mode 100644index 000000000..7653e4b8a--- /dev/null+++ b/examples/tilemap-demo/assets/scenes/wang-map.esscene.meta@@ -0,0 +1,6 @@+{+ "uuid": "63221cdb-715c-47c2-a858-fa06cda18fe2",+ "version": "2.0",+ "type": "scene",+ "importer": {}+}diff --git a/examples/tilemap-demo/assets/tilesets/wang-tiles.png b/examples/tilemap-demo/assets/tilesets/wang-tiles.pngnew file mode 100644index 000000000..4afc8af50Binary files /dev/null and b/examples/tilemap-demo/assets/tilesets/wang-tiles.png differdiff --git a/examples/tilemap-demo/assets/tilesets/wang-tiles.png.meta b/examples/tilemap-demo/assets/tilesets/wang-tiles.png.metanew file mode 100644index 000000000..9e4972218--- /dev/null+++ b/examples/tilemap-demo/assets/tilesets/wang-tiles.png.meta@@ -0,0 +1,17 @@+{+ "uuid": "6556711b-c60d-4f42-8f3e-834a5cb3ded4",+ "version": "2.0",+ "type": "texture",+ "importer": {+ "maxSize": 2048,+ "filterMode": "nearest",+ "wrapMode": "clamp",+ "premultiplyAlpha": false,+ "sliceBorder": {+ "left": 0,+ "right": 0,+ "top": 0,+ "bottom": 0+ }+ }+}diff --git a/examples/tilemap-demo/assets/tilesets/wang.estileset b/examples/tilemap-demo/assets/tilesets/wang.estilesetnew file mode 100644index 000000000..e7405f541--- /dev/null+++ b/examples/tilemap-demo/assets/tilesets/wang.estileset@@ -0,0 +1,527 @@+{+ "version": "1",+ "texture": "@uuid:6556711b-c60d-4f42-8f3e-834a5cb3ded4",+ "tileWidth": 32,+ "tileHeight": 32,+ "columns": 12,+ "margin": 0,+ "spacing": 0,+ "tileCount": 45,+ "terrains": [+ {+ "name": "Terrain",+ "mode": "wang",+ "colors": [+ {+ "name": "Grass",+ "color": "#5a9e3f"+ },+ {+ "name": "Sand",+ "color": "#d9c48a"+ },+ {+ "name": "Water",+ "color": "#3a7ec8"+ }+ ]+ }+ ],+ "tiles": {+ "1": {+ "terrain": {+ "set": 0,+ "corners": [+ 1,+ 1,+ 1,+ 1+ ]+ }+ },+ "2": {+ "terrain": {+ "set": 0,+ "corners": [+ 1,+ 1,+ 1,+ 2+ ]+ }+ },+ "3": {+ "terrain": {+ "set": 0,+ "corners": [+ 1,+ 1,+ 2,+ 1+ ]+ }+ },+ "4": {+ "terrain": {+ "set": 0,+ "corners": [+ 1,+ 1,+ 2,+ 2+ ]+ }+ },+ "5": {+ "terrain": {+ "set": 0,+ "corners": [+ 1,+ 2,+ 1,+ 1+ ]+ }+ },+ "6": {+ "terrain": {+ "set": 0,+ "corners": [+ 1,+ 2,+ 1,+ 2+ ]+ }+ },+ "7": {+ "terrain": {+ "set": 0,+ "corners": [+ 1,+ 2,+ 2,+ 1+ ]+ }+ },+ "8": {+ "terrain": {+ "set": 0,+ "corners": [+ 1,+ 2,+ 2,+ 2+ ]+ }+ },+ "9": {+ "terrain": {+ "set": 0,+ "corners": [+ 2,+ 1,+ 1,+ 1+ ]+ }+ },+ "10": {+ "terrain": {+ "set": 0,+ "corners": [+ 2,+ 1,+ 1,+ 2+ ]+ }+ },+ "11": {+ "terrain": {+ "set": 0,+ "corners": [+ 2,+ 1,+ 2,+ 1+ ]+ }+ },+ "12": {+ "terrain": {+ "set": 0,+ "corners": [+ 2,+ 1,+ 2,+ 2+ ]+ }+ },+ "13": {+ "terrain": {+ "set": 0,+ "corners": [+ 2,+ 2,+ 1,+ 1+ ]+ }+ },+ "14": {+ "terrain": {+ "set": 0,+ "corners": [+ 2,+ 2,+ 1,+ 2+ ]+ }+ },+ "15": {+ "terrain": {+ "set": 0,+ "corners": [+ 2,+ 2,+ 2,+ 1+ ]+ }+ },+ "16": {+ "terrain": {+ "set": 0,+ "corners": [+ 1,+ 1,+ 1,+ 3+ ]+ }+ },+ "17": {+ "terrain": {+ "set": 0,+ "corners": [+ 1,+ 1,+ 3,+ 1+ ]+ }+ },+ "18": {+ "terrain": {+ "set": 0,+ "corners": [+ 1,+ 1,+ 3,+ 3+ ]+ }+ },+ "19": {+ "terrain": {+ "set": 0,+ "corners": [+ 1,+ 3,+ 1,+ 1+ ]+ }+ },+ "20": {+ "terrain": {+ "set": 0,+ "corners": [+ 1,+ 3,+ 1,+ 3+ ]+ }+ },+ "21": {+ "terrain": {+ "set": 0,+ "corners": [+ 1,+ 3,+ 3,+ 1+ ]+ }+ },+ "22": {+ "terrain": {+ "set": 0,+ "corners": [+ 1,+ 3,+ 3,+ 3+ ]+ }+ },+ "23": {+ "terrain": {+ "set": 0,+ "corners": [+ 3,+ 1,+ 1,+ 1+ ]+ }+ },+ "24": {+ "terrain": {+ "set": 0,+ "corners": [+ 3,+ 1,+ 1,+ 3+ ]+ }+ },+ "25": {+ "terrain": {+ "set": 0,+ "corners": [+ 3,+ 1,+ 3,+ 1+ ]+ }+ },+ "26": {+ "terrain": {+ "set": 0,+ "corners": [+ 3,+ 1,+ 3,+ 3+ ]+ }+ },+ "27": {+ "terrain": {+ "set": 0,+ "corners": [+ 3,+ 3,+ 1,+ 1+ ]+ }+ },+ "28": {+ "terrain": {+ "set": 0,+ "corners": [+ 3,+ 3,+ 1,+ 3+ ]+ }+ },+ "29": {+ "terrain": {+ "set": 0,+ "corners": [+ 3,+ 3,+ 3,+ 1+ ]+ }+ },+ "30": {+ "terrain": {+ "set": 0,+ "corners": [+ 2,+ 2,+ 2,+ 2+ ]+ }+ },+ "31": {+ "terrain": {+ "set": 0,+ "corners": [+ 2,+ 2,+ 2,+ 3+ ]+ }+ },+ "32": {+ "terrain": {+ "set": 0,+ "corners": [+ 2,+ 2,+ 3,+ 2+ ]+ }+ },+ "33": {+ "terrain": {+ "set": 0,+ "corners": [+ 2,+ 2,+ 3,+ 3+ ]+ }+ },+ "34": {+ "terrain": {+ "set": 0,+ "corners": [+ 2,+ 3,+ 2,+ 2+ ]+ }+ },+ "35": {+ "terrain": {+ "set": 0,+ "corners": [+ 2,+ 3,+ 2,+ 3+ ]+ }+ },+ "36": {+ "terrain": {+ "set": 0,+ "corners": [+ 2,+ 3,+ 3,+ 2+ ]+ }+ },+ "37": {+ "terrain": {+ "set": 0,+ "corners": [+ 2,+ 3,+ 3,+ 3+ ]+ }+ },+ "38": {+ "terrain": {+ "set": 0,+ "corners": [+ 3,+ 2,+ 2,+ 2+ ]+ }+ },+ "39": {+ "terrain": {+ "set": 0,+ "corners": [+ 3,+ 2,+ 2,+ 3+ ]+ }+ },+ "40": {+ "terrain": {+ "set": 0,+ "corners": [+ 3,+ 2,+ 3,+ 2+ ]+ }+ },+ "41": {+ "terrain": {+ "set": 0,+ "corners": [+ 3,+ 2,+ 3,+ 3+ ]+ }+ },+ "42": {+ "terrain": {+ "set": 0,+ "corners": [+ 3,+ 3,+ 2,+ 2+ ]+ }+ },+ "43": {+ "terrain": {+ "set": 0,+ "corners": [+ 3,+ 3,+ 2,+ 3+ ]+ }+ },+ "44": {+ "terrain": {+ "set": 0,+ "corners": [+ 3,+ 3,+ 3,+ 2+ ]+ }+ },+ "45": {+ "terrain": {+ "set": 0,+ "corners": [+ 3,+ 3,+ 3,+ 3+ ]+ }+ }+ }+}diff --git a/examples/tilemap-demo/assets/tilesets/wang.estileset.meta b/examples/tilemap-demo/assets/tilesets/wang.estileset.metanew file mode 100644index 000000000..5175c4715--- /dev/null+++ b/examples/tilemap-demo/assets/tilesets/wang.estileset.meta@@ -0,0 +1,6 @@+{+ "uuid": "85d000f8-d6c7-4840-8442-a99535375017",+ "version": "2.0",+ "type": "tileset",+ "importer": {}+}diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.mdindex 8e3d6630c..db7d8b464 100644--- a/sdk/etc/index.api.md+++ b/sdk/etc/index.api.md@@ -1,7 +1,7 @@# API surface — esengine/index<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 1236 stable · 17 beta · 1 deprecated+Symbols: 1242 stable · 17 beta · 1 deprecated## ABI_LAYOUT_HASH — const```@@ -6106,6 +6106,12 @@ numberRecord<string, string | number>```+## TerrainColor — interface+```+color: string+name: string+```+## TerrainIndex — interface```byMask: Map<number, number>@@ -6120,7 +6126,7 @@ tileTerrain: Map<number, number>## TerrainMode — type```-'edge' | 'corner'+'edge' | 'corner' | 'wang'```## Text — const@@ -6564,6 +6570,7 @@ tileShapes: Map<number, ResolvedTileCollision>## TilesetTerrain — interface```color: string | undefined+colors: TerrainColor[] | undefinedmode: TerrainModename: string```@@ -6579,7 +6586,8 @@ terrain: TilesetTileTerrain | undefined## TilesetTileTerrain — interface```-mask: number+corners: number[] | undefined+mask: number | undefinedset: number```@@ -7411,6 +7419,17 @@ x: numbery: number```+## WangIndex — interface+```+byKey: Map<number, number>+```++## WangIndices — interface+```+sets: Map<number, WangIndex>+tileTerrain: Map<number, number>+```+## WeChatSideModuleFactories — type```Partial<Record<SideModuleId, EmscriptenFactory>>@@ -7756,6 +7775,11 @@ BtPlugin(init?: UIVisualInit): UIVisualData```+## buildWangIndices — function+```+(asset: TilesetAsset): WangIndices+```+## builtinShaderTemplate — function```(id: string): BuiltinShaderTemplate | undefined@@ -8806,6 +8830,11 @@ NavPlugin(flags: TileFlags): Perm```+## packCorners — function+```+(tl: number, tr: number, br: number, bl: number): number+```+## parseAnimClipAsset — function```(raw: any): AnimClipAssetData@@ -9126,6 +9155,11 @@ ReplicationPlugin(tilesets: ResolvedTileset[]): TilesetModel```+## resolveWang — function+```+(index: WangIndex, corners: readonly number[]): number+```+## rotateFlagsCW — function```(flags: TileFlags): TileFlagsdiff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.mdindex b0c70cca5..4a5238e39 100644--- a/sdk/etc/index.node.api.md+++ b/sdk/etc/index.node.api.md@@ -1,7 +1,7 @@# API surface — esengine/index.node<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 1235 stable · 19 beta · 1 deprecated+Symbols: 1241 stable · 19 beta · 1 deprecated## ANCHOR_AXES — const```@@ -6101,6 +6101,12 @@ numberRecord<string, string | number>```+## TerrainColor — interface+```+color: string+name: string+```+## TerrainIndex — interface```byMask: Map<number, number>@@ -6115,7 +6121,7 @@ tileTerrain: Map<number, number>## TerrainMode — type```-'edge' | 'corner'+'edge' | 'corner' | 'wang'```## Text — const@@ -6559,6 +6565,7 @@ tileShapes: Map<number, ResolvedTileCollision>## TilesetTerrain — interface```color: string | undefined+colors: TerrainColor[] | undefinedmode: TerrainModename: string```@@ -6574,7 +6581,8 @@ terrain: TilesetTileTerrain | undefined## TilesetTileTerrain — interface```-mask: number+corners: number[] | undefined+mask: number | undefinedset: number```@@ -7406,6 +7414,17 @@ x: numbery: number```+## WangIndex — interface+```+byKey: Map<number, number>+```++## WangIndices — interface+```+sets: Map<number, WangIndex>+tileTerrain: Map<number, number>+```+## WeChatSideModuleFactories — type```Partial<Record<SideModuleId, EmscriptenFactory>>@@ -7751,6 +7770,11 @@ BtPlugin(init?: UIVisualInit): UIVisualData```+## buildWangIndices — function+```+(asset: TilesetAsset): WangIndices+```+## builtinShaderTemplate — function```(id: string): BuiltinShaderTemplate | undefined@@ -8811,6 +8835,11 @@ NodePlatformAdapter(flags: TileFlags): Perm```+## packCorners — function+```+(tl: number, tr: number, br: number, bl: number): number+```+## parseAnimClipAsset — function```(raw: any): AnimClipAssetData@@ -9131,6 +9160,11 @@ ReplicationPlugin(tilesets: ResolvedTileset[]): TilesetModel```+## resolveWang — function+```+(index: WangIndex, corners: readonly number[]): number+```+## rotateFlagsCW — function```(flags: TileFlags): TileFlagsdiff --git a/sdk/src/core-content.ts b/sdk/src/core-content.tsindex 680c11941..375cd95a6 100644--- a/sdk/src/core-content.ts+++ b/sdk/src/core-content.ts@@ -423,6 +423,9 @@ export {canonicalMask,buildTerrainIndices,resolveAutotile,+ packCorners,+ buildWangIndices,+ resolveWang,TILE_ID_MASK,TILE_FLIP_H,TILE_FLIP_V,@@ -464,10 +467,13 @@ export {type Vec2Like,type TilesetAnimFrame,type TerrainMode,+ type TerrainColor,type TilesetTerrain,type TilesetTileTerrain,type TerrainIndex,type TerrainIndices,+ type WangIndex,+ type WangIndices,type ApplyTilesetRefs,} from './tilemap';diff --git a/sdk/src/tilemap/autotile.ts b/sdk/src/tilemap/autotile.tsindex 40cf54c80..723a8d50c 100644--- a/sdk/src/tilemap/autotile.ts+++ b/sdk/src/tilemap/autotile.ts@@ -79,8 +79,11 @@ export function buildTerrainIndices(asset: TilesetAsset): TerrainIndices {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';+ // Peering (edge/corner) only — wang sets carry per-corner colors, not a mask, and+ // resolve through buildWangIndices; skip them (and any tile missing a mask).+ if (mode === 'wang' || t.mask === undefined) continue;+ tileTerrain.set(id, t.set);let index = sets.get(t.set);if (!index) {index = { mode, byMask: new Map() };@@ -121,3 +124,71 @@ export function resolveAutotile(index: TerrainIndex, neighbors: readonly boolean}return best;}++// ── Corner (Wang) terrain ────────────────────────────────────────────────────+// The modern model: a tile carries a COLOR at each of its 4 corners. A cell is resolved+// from the 4 colors on its corners (a half-cell "corner grid"), so one set blends many+// terrains. Corner order everywhere is [top-left, top-right, bottom-right, bottom-left].++/** Pack 4 corner color indices into one lookup key (8 bits each; up to 255 colors). */+export function packCorners(tl: number, tr: number, br: number, bl: number): number {+ // The low 3 bytes stay in int32 range; ADD the top byte (a plain multiply) so the OR's+ // int32 coercion can't wrap the key negative.+ return ((tl & 0xff) | ((tr & 0xff) << 8) | ((br & 0xff) << 16)) + ((bl & 0xff) * 0x1000000);+}++/** A wang set's resolver: packed 4-corner key → the tile id to draw. */+export interface WangIndex {+ byKey: Map<number, number>;+}++/** Built lookup over a tileset's wang terrains: per-set resolver + reverse tile→set. */+export interface WangIndices {+ sets: Map<number, WangIndex>;+ tileTerrain: Map<number, number>;+}++/** Build the corner-match resolver tables for a tileset's `wang` sets (first tile wins a dup). */+export function buildWangIndices(asset: TilesetAsset): WangIndices {+ const sets = new Map<number, WangIndex>();+ 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 || !t.corners || (terrains[t.set]?.mode ?? 'edge') !== 'wang') continue;+ tileTerrain.set(id, t.set);+ let index = sets.get(t.set);+ if (!index) { index = { byKey: new Map() }; sets.set(t.set, index); }+ const k = packCorners(t.corners[0], t.corners[1], t.corners[2], t.corners[3]);+ if (!index.byKey.has(k)) index.byKey.set(k, id);+ }+ return { sets, tileTerrain };+}++/** How many of the 4 corners differ between two packed keys. */+function cornerDist(a: number, b: number): number {+ let d = 0;+ for (let s = 0; s < 32; s += 8) {+ if (((a >>> s) & 0xff) !== ((b >>> s) & 0xff)) d++;+ }+ return d;+}++/**+ * Pick the tile whose 4 corner colors match `corners` ([TL, TR, BR, BL]); when no tile has+ * the exact combination, the nearest by corner-mismatch count is used, so a partial wang+ * set still paints. Returns 0 if the set is empty.+ */+export function resolveWang(index: WangIndex, corners: readonly number[]): number {+ const key = packCorners(corners[0] ?? 0, corners[1] ?? 0, corners[2] ?? 0, corners[3] ?? 0);+ const exact = index.byKey.get(key);+ if (exact !== undefined) return exact;+ let best = 0;+ let bestDist = Infinity;+ for (const [k, id] of index.byKey) {+ const d = cornerDist(k, key);+ if (d < bestDist) { bestDist = d; best = id; }+ }+ return best;+}diff --git a/sdk/src/tilemap/index.ts b/sdk/src/tilemap/index.tsindex c49dd7ffa..65d889857 100644--- a/sdk/src/tilemap/index.ts+++ b/sdk/src/tilemap/index.ts@@ -33,7 +33,7 @@ export {export {TILESET_FORMAT_VERSION, parseTileset, serializeTileset, createTileset, collidableTileIds,type TilesetAsset, type TilesetTile, type TilesetCollision, type TileCollisionShape, type TilesetAnimFrame,- type TerrainMode, type TilesetTerrain, type TilesetTileTerrain,+ type TerrainMode, type TerrainColor, type TilesetTerrain, type TilesetTileTerrain,} from './tilesetAsset';export {resolveTilesetModel,@@ -42,7 +42,8 @@ export {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,+ packCorners, buildWangIndices, resolveWang,+ type TerrainIndex, type TerrainIndices, type WangIndex, type WangIndices,} from './autotile';export {registerTilemapSource, getTilemapSource, clearTilemapSourceCache,diff --git a/sdk/src/tilemap/tilesetAsset.ts b/sdk/src/tilemap/tilesetAsset.tsindex 0d1e8e076..5847e006b 100644--- a/sdk/src/tilemap/tilesetAsset.ts+++ b/sdk/src/tilemap/tilesetAsset.ts@@ -53,24 +53,42 @@ export interface TilesetAnimFrame {}/**- * 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.+ * How a terrain's tiles match their neighbours. `edge` = 4-bit N/E/S/W peering (16-tile+ * sets, good for ground/walls); `corner` = the 8-bit "corners and sides" blob (up to 47+ * tiles, smooth blobby terrain) — both are single-terrain peering masks. `wang` = the+ * modern corner (Wang) model: each tile assigns a COLOR to each of its 4 corners, so one+ * set blends MANY terrains (grass↔sand↔water) and paints on a half-cell corner grid.+ * See `autotile.ts` for the resolvers.*/-export type TerrainMode = 'edge' | 'corner';+export type TerrainMode = 'edge' | 'corner' | 'wang';++/** One terrain color in a `wang` set (a corner can carry this). */+export interface TerrainColor {+ name: string;+ /** CSS color for the authoring dot / brush swatch. */+ color: string;+}/** 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. */+ /** Authoring tint for a peering (edge/corner) terrain (CSS color); cosmetic. */color?: string;+ /** The corner-color palette for a `wang` set (index 0 in `corners` = none/empty). */+ colors?: TerrainColor[];}-/** A tile's membership in a terrain: which set, and its peering bitmask (see `autotile.ts`). */+/**+ * A tile's membership in a terrain set. Edge/corner sets use `mask` (a peering bitmask,+ * see `autotile.ts`); a `wang` set uses `corners` — the color index at each corner in+ * [top-left, top-right, bottom-right, bottom-left] order (0 = none, else 1-based into the+ * set's {@link TilesetTerrain.colors}).+ */export interface TilesetTileTerrain {set: number;- mask: number;+ mask?: number;+ corners?: number[];}/** Per-tile metadata. Sparse — only tiles that carry any of these appear in the map. */@@ -180,9 +198,15 @@ export function parseTileset(raw: any): TilesetAsset {if (frames.length > 0) tile.animation = frames;}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 };+ && Number.isInteger(t.terrain.set) && t.terrain.set >= 0) {+ const tt: TilesetTileTerrain = { set: t.terrain.set };+ if (Number.isInteger(t.terrain.mask) && t.terrain.mask >= 0) tt.mask = t.terrain.mask;+ if (Array.isArray(t.terrain.corners) && t.terrain.corners.length === 4+ && t.terrain.corners.every((c: any) => Number.isInteger(c) && c >= 0)) {+ tt.corners = [t.terrain.corners[0], t.terrain.corners[1], t.terrain.corners[2], t.terrain.corners[3]];+ }+ // A membership needs at least one of the two payloads (peering mask or wang corners).+ if (tt.mask !== undefined || tt.corners !== undefined) tile.terrain = tt;}if (typeof t.probability === 'number' && Number.isFinite(t.probability)&& t.probability >= 0 && t.probability !== 1) {@@ -194,11 +218,20 @@ export function parseTileset(raw: any): TilesetAsset {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 } : {}),- }))+ .map((t: any): TilesetTerrain => {+ const mode: TerrainMode = t.mode === 'corner' ? 'corner' : t.mode === 'wang' ? 'wang' : 'edge';+ const colors: TerrainColor[] = Array.isArray(t.colors)+ ? t.colors+ .filter((c: any) => c && typeof c.color === 'string')+ .map((c: any): TerrainColor => ({ name: typeof c.name === 'string' ? c.name : '', color: c.color }))+ : [];+ return {+ name: t.name,+ mode,+ ...(typeof t.color === 'string' ? { color: t.color } : {}),+ ...(colors.length > 0 ? { colors } : {}),+ };+ }): [];return {version: typeof raw?.version === 'string' ? raw.version : TILESET_FORMAT_VERSION,diff --git a/sdk/tests/wangTerrain.test.ts b/sdk/tests/wangTerrain.test.tsnew file mode 100644index 000000000..205f7804a--- /dev/null+++ b/sdk/tests/wangTerrain.test.ts@@ -0,0 +1,94 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+import { describe, it, expect } from 'vitest';+import { parseTileset, serializeTileset } from '../src/tilemap/tilesetAsset';+import {+ packCorners, buildWangIndices, resolveWang, buildTerrainIndices,+} from '../src/tilemap/autotile';++// A minimal wang tileset: one set with colors [_, grass(1), sand(2)], and tiles covering+// a few corner combinations. Corner order is [TL, TR, BR, BL].+const wangRaw = {+ version: '1', texture: '@uuid:x', tileWidth: 16, tileHeight: 16, columns: 4, margin: 0, spacing: 0,+ terrains: [+ { name: 'Ground', mode: 'wang', colors: [{ name: 'Grass', color: '#3a3' }, { name: 'Sand', color: '#dc8' }] },+ { name: 'Wall', mode: 'edge' },+ ],+ tiles: {+ 1: { terrain: { set: 0, corners: [1, 1, 1, 1] } }, // all grass+ 2: { terrain: { set: 0, corners: [2, 2, 2, 2] } }, // all sand+ 3: { terrain: { set: 0, corners: [1, 2, 2, 1] } }, // grass left, sand right+ 4: { terrain: { set: 0, corners: [1, 1, 2, 2] } }, // grass top, sand bottom+ 9: { terrain: { set: 1, mask: 1 } }, // a peering tile in another set+ },+};++describe('packCorners', () => {+ it('is a stable, collision-free key for distinct corner combos', () => {+ expect(packCorners(1, 1, 1, 1)).toBe(packCorners(1, 1, 1, 1));+ expect(packCorners(1, 2, 2, 1)).not.toBe(packCorners(1, 1, 2, 2));+ // the top corner (BL) still yields a positive integer (no signed << 24 overflow)+ expect(packCorners(0, 0, 0, 255)).toBeGreaterThan(0);+ expect(packCorners(0, 0, 0, 200)).toBeGreaterThan(0);+ });+});++describe('wang round-trip', () => {+ it('parses + serializes colors and per-tile corners', () => {+ const a = parseTileset(wangRaw);+ expect(a.terrains?.[0]).toEqual({+ name: 'Ground', mode: 'wang',+ colors: [{ name: 'Grass', color: '#3a3' }, { name: 'Sand', color: '#dc8' }],+ });+ expect(a.tiles[3].terrain).toEqual({ set: 0, corners: [1, 2, 2, 1] });+ // survives a serialize→parse cycle unchanged+ const b = parseTileset(serializeTileset(a));+ expect(b.tiles[3].terrain).toEqual({ set: 0, corners: [1, 2, 2, 1] });+ expect(b.terrains?.[0].colors).toHaveLength(2);+ });++ it('drops a terrain membership with neither a mask nor corners', () => {+ const a = parseTileset({+ ...wangRaw,+ tiles: { 7: { terrain: { set: 0 } }, 8: { terrain: { set: 0, corners: [1, 0, 0, 1] } } },+ });+ expect(a.tiles[7]).toBeUndefined();+ expect(a.tiles[8].terrain).toEqual({ set: 0, corners: [1, 0, 0, 1] });+ });+});++describe('buildWangIndices + resolveWang', () => {+ const asset = parseTileset(wangRaw);++ it('indexes only wang tiles (peering tiles stay out)', () => {+ const wi = buildWangIndices(asset);+ expect(wi.sets.has(0)).toBe(true);+ expect(wi.sets.has(1)).toBe(false); // set 1 is 'edge', not wang+ expect(wi.tileTerrain.get(3)).toBe(0);+ expect(wi.tileTerrain.has(9)).toBe(false);+ });++ it('the peering resolver ignores wang tiles (no cross-pollution)', () => {+ const ti = buildTerrainIndices(asset);+ expect(ti.sets.has(0)).toBe(false); // wang set absent from peering index+ expect(ti.tileTerrain.has(1)).toBe(false);+ });++ it('resolves an exact corner match', () => {+ const wi = buildWangIndices(asset);+ const set = wi.sets.get(0)!;+ expect(resolveWang(set, [1, 1, 1, 1])).toBe(1); // all grass+ expect(resolveWang(set, [2, 2, 2, 2])).toBe(2); // all sand+ expect(resolveWang(set, [1, 2, 2, 1])).toBe(3); // grass|sand vertical split+ expect(resolveWang(set, [1, 1, 2, 2])).toBe(4); // grass|sand horizontal split+ });++ it('falls back to the nearest tile by corner mismatch', () => {+ const wi = buildWangIndices(asset);+ const set = wi.sets.get(0)!;+ // [1,1,1,2] differs from tile 1 (all grass) in 1 corner, from others in >=2 → tile 1+ expect(resolveWang(set, [1, 1, 1, 2])).toBe(1);+ // [2,2,2,1] is 1 corner from tile 2 (all sand) → tile 2+ expect(resolveWang(set, [2, 2, 2, 1])).toBe(2);+ });+});