Skip to content

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

feat(editor): Tilemap painter — viewport painting + brush palette (REARCH_TILEMAP T3b)

esengine84661273b0f3
diff --git a/desktop/src/engine/SceneCommands.ts b/desktop/src/engine/SceneCommands.ts
index 045912616..04c50734b 100644
--- a/desktop/src/engine/SceneCommands.ts
+++ b/desktop/src/engine/SceneCommands.ts
@@ -119,6 +119,9 @@ export class SceneCommandsImpl {
// the recorder returns false (observe-only) so the edit still lands normally.
// Kept generic: SceneCommands knows nothing about timelines.
private editHook: EditHook | null = null;
+ // An in-progress tilemap paint stroke: the chunk blob snapshotted at stroke start
+ // ({@link beginTilePaint}), committed as one undo step at {@link endTilePaint}.
+ private tilePaint: { sourceId: number; before: string } | null = null;
constructor(
private readonly model: SceneModelImpl,
@@ -456,9 +459,41 @@ export class SceneCommandsImpl {
if (edits.length === 0) return;
const rt = this.model.runtimeFor(sourceId);
if (rt === undefined) return;
-
const before = TilemapAPI.exportChunks(rt);
for (const e of edits) TilemapAPI.setTile(rt, e.x, e.y, e.tileId);
+ this.commitTilePaint_(sourceId, before);
+ }
+
+ /**
+ * Begin a live paint stroke (a viewport brush/erase drag). Snapshots the chunk
+ * blob now; paint live with {@link paintTileLive}; commit one undo step with
+ * {@link endTilePaint}. Mirrors the field-edit gesture (begin/…/end) so a drag is
+ * one undo step while staying live in the viewport.
+ */
+ beginTilePaint(sourceId: EntityId): void {
+ const rt = this.model.runtimeFor(sourceId);
+ this.tilePaint = rt === undefined ? null : { sourceId, before: TilemapAPI.exportChunks(rt) };
+ }
+
+ /** Paint one tile live (no model write / no undo) during an open stroke. */
+ paintTileLive(sourceId: EntityId, x: number, y: number, tileId: number): void {
+ const rt = this.model.runtimeFor(sourceId);
+ if (rt !== undefined) TilemapAPI.setTile(rt, x, y, tileId);
+ }
+
+ /** Commit the open paint stroke as one undo step (no-op if nothing changed). */
+ endTilePaint(): void {
+ const s = this.tilePaint;
+ this.tilePaint = null;
+ if (s) this.commitTilePaint_(s.sourceId, s.before);
+ }
+
+ // Shared commit: snapshot the post-edit blob, write it to the model (the truth
+ // for save + rebuild), and record one undo step whose closures re-resolve the
+ // runtime entity (it changes across a play→stop rebuild) and re-import the blob.
+ private commitTilePaint_(sourceId: EntityId, before: string): void {
+ const rt = this.model.runtimeFor(sourceId);
+ if (rt === undefined) return;
const after = TilemapAPI.exportChunks(rt);
if (after === before) return; // painted the same ids that were already there
diff --git a/desktop/src/layout/DockLayout.tsx b/desktop/src/layout/DockLayout.tsx
index 2c1f05f74..89504ecc1 100644
--- a/desktop/src/layout/DockLayout.tsx
+++ b/desktop/src/layout/DockLayout.tsx
@@ -16,6 +16,7 @@ import { OutputLog } from '@/panels/OutputLog';
import { GamePanel } from '@/panels/GamePanel';
import { Sequencer } from '@/panels/Sequencer';
import { TilesetEditor } from '@/panels/TilesetEditor';
+import { TilemapPainter } from '@/panels/TilemapPainter';
import { dockApi } from '@/layout/dockApi';
// Each dock panel is a thin wrapper so dockview owns mount/unmount.
@@ -27,6 +28,7 @@ const components: Record<string, FC<IDockviewPanelProps>> = {
log: () => <OutputLog />,
sequencer: () => <Sequencer />,
tileset: () => <TilesetEditor />,
+ tilemap: () => <TilemapPainter />,
// The "Game" view (isolated play realm) — added on Play, removed on Stop.
game: () => <GamePanel />,
};
@@ -99,6 +101,18 @@ function ensureTileset(api: DockviewReadyEvent['api']) {
});
}
+// The Tilemap painter — same bottom-dock tab treatment.
+function ensureTilemap(api: DockviewReadyEvent['api']) {
+ if (api.getPanel('tilemap')) return;
+ const ref = api.getPanel('content') ? 'content' : api.getPanel('tileset') ? 'tileset' : undefined;
+ api.addPanel({
+ id: 'tilemap',
+ component: 'tilemap',
+ title: 'Tilemap',
+ position: ref ? { referencePanel: ref, direction: 'within' } : undefined,
+ });
+}
+
// A collapse/expand chevron in every dock group's header (the design's `.pcol`).
// Collapses the group to its tab bar by height; hidden on the Viewport/Game group
// (the center stage isn't an accordion). State follows the live group height, so
@@ -146,6 +160,7 @@ export function DockLayout() {
// adding it doesn't steal the bottom dock's active tab on load.
ensureSequencer(api);
ensureTileset(api);
+ ensureTilemap(api);
api.getPanel('content')?.api.setActive();
// Persist the dock arrangement so it survives reloads — a real editor habit.
diff --git a/desktop/src/main.tsx b/desktop/src/main.tsx
index c6456c3c2..749ca9c9c 100644
--- a/desktop/src/main.tsx
+++ b/desktop/src/main.tsx
@@ -23,6 +23,7 @@ import './theme/viewport.css';
import './theme/content.css';
import './theme/sequencer.css';
import './theme/tileset.css';
+import './theme/tilemap.css';
import './theme/chrome.css';
import './theme/menus.css';
import './theme/settings.css';
diff --git a/desktop/src/panels/ContentBrowser.tsx b/desktop/src/panels/ContentBrowser.tsx
index 87cf83b44..ed7a88b53 100644
--- a/desktop/src/panels/ContentBrowser.tsx
+++ b/desktop/src/panels/ContentBrowser.tsx
@@ -12,6 +12,7 @@ import { useSelection } from '@/store/selectionStore';
import { IMAGE_RE, assetTypeOf as assetType, TYPE_CODE } from '@/project/assetMeta';
import { openAnimationClip } from '@/timeline/openClip';
import { openTileset, createTilesetFromTexture } from '@/tileset/openTileset';
+import { createTilemapFromTileset } from '@/tilemap/createTilemap';
import { fsRefresh } from '@/project/fsWatch';
import type { DirEntry } from '@/project/format';
import type { AssetType } from '@/types';
@@ -455,6 +456,7 @@ export function ContentBrowser() {
const { path, entry } = ctx.target;
const isScene = !entry.isDir && assetType(entry.name) === 'scene';
const isTexture = !entry.isDir && (assetType(entry.name) === 'texture' || assetType(entry.name) === 'sprite');
+ const isTileset = !entry.isDir && assetType(entry.name) === 'tileset';
const ref = entry.isDir ? null : ProjectStore.assetRef(path);
return [
...(entry.isDir || isScene
@@ -463,6 +465,9 @@ export function ContentBrowser() {
...(isTexture
? [{ label: 'Create Tileset', onClick: () => void createTilesetFromTexture(path) }]
: []),
+ ...(isTileset
+ ? [{ label: 'Create Tilemap', onClick: () => void createTilemapFromTileset(path) }]
+ : []),
{ label: 'Rename', onClick: () => setRenaming(path) },
{ label: 'Duplicate', onClick: () => void duplicate(path) },
{ sep: true },
diff --git a/desktop/src/panels/TilemapPainter.tsx b/desktop/src/panels/TilemapPainter.tsx
new file mode 100644
index 000000000..54099c471
--- /dev/null
+++ b/desktop/src/panels/TilemapPainter.tsx
@@ -0,0 +1,140 @@
+// SPDX-License-Identifier: LicenseRef-PolyForm-Noncommercial-1.0.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file TilemapPainter.tsx
+ * @brief The Tilemap painter panel (REARCH_TILEMAP T3b) — 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.
+ */
+
+import { useEffect, useState } from 'react';
+import { Brush, Eraser, Square, Pipette } from 'lucide-react';
+import { parseTileset, type TilesetAsset } from 'esengine';
+import { useTilemapPaint, type PaintTool } from '@/store/tilemapPaintStore';
+import { useSelection } from '@/store/selectionStore';
+import { SceneModel } from '@/engine/SceneModel';
+import { ProjectStore } from '@/project/ProjectStore';
+
+function colsFor(width: number, tileW: number, margin: number, spacing: number): number {
+ const stride = tileW + spacing;
+ return stride > 0 ? Math.max(1, Math.floor((width - margin + spacing) / stride)) : 1;
+}
+function rowsFor(height: number, tileH: number, margin: number, spacing: number): number {
+ const stride = tileH + spacing;
+ return stride > 0 ? Math.max(0, Math.floor((height - margin + spacing) / stride)) : 0;
+}
+
+const TOOLS: { id: PaintTool; icon: typeof Brush; label: string }[] = [
+ { id: 'brush', icon: Brush, label: '画笔' },
+ { id: 'erase', icon: Eraser, label: '擦除' },
+ { id: 'rect', icon: Square, label: '矩形' },
+ { id: 'eyedropper', icon: Pipette, label: '吸管' },
+];
+
+/** Resolve the .estileset path a selected TilemapLayer references (its `tilesetAsset` @uuid). */
+function selectedTilemapTilesetPath(selectedId: number | null): string | null {
+ if (selectedId == null) return null;
+ const e = SceneModel.entityBySource(selectedId);
+ const layer = e?.components.find((c) => c.type === 'TilemapLayer');
+ if (!layer) return null;
+ const ref = (layer.data as Record<string, unknown>).tilesetAsset;
+ return typeof ref === 'string' ? (ProjectStore.assetInfo(ref)?.path ?? null) : null;
+}
+
+export function TilemapPainter() {
+ const { tilesetPath, brushTileId, tool, setTileset, setBrush, setTool } = useTilemapPaint();
+ const selectedId = useSelection((s) => s.selectedId);
+ const hasTilemap = selectedId != null
+ && !!SceneModel.entityBySource(selectedId)?.components.some((c) => c.type === 'TilemapLayer');
+
+ // Selecting a TilemapLayer loads its referenced .estileset as the active palette.
+ useEffect(() => {
+ const path = selectedTilemapTilesetPath(selectedId);
+ if (path && path !== tilesetPath) setTileset(path);
+ }, [selectedId, tilesetPath, setTileset]);
+
+ const [asset, setAsset] = useState<TilesetAsset | null>(null);
+ useEffect(() => {
+ let alive = true;
+ if (!tilesetPath) { setAsset(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); }
+ })();
+ return () => { alive = false; };
+ }, [tilesetPath]);
+
+ 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]);
+
+ if (!hasTilemap) {
+ return (
+ <div className="tp-empty">
+ <p>未选择瓦片地图</p>
+ <p className="tp-hint">在内容浏览器右键 .estileset → 新建瓦片地图,或在大纲里选中一个瓦片地图实体</p>
+ </div>
+ );
+ }
+
+ const tw = asset?.tileWidth ?? 16;
+ const th = asset?.tileHeight ?? 16;
+ const mg = asset?.margin ?? 0;
+ const sp = asset?.spacing ?? 0;
+ const cols = natural ? colsFor(natural.w, tw, mg, sp) : (asset?.columns ?? 1);
+ const rows = natural ? rowsFor(natural.h, th, mg, sp) : 0;
+
+ const cells = [];
+ if (texUrl && natural) {
+ for (let row = 0; row < rows; row++) {
+ for (let col = 0; col < cols; col++) {
+ const id = row * cols + col + 1;
+ cells.push(
+ <div
+ key={id}
+ className={'tp-cell' + (id === brushTileId ? ' 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'); }}
+ />,
+ );
+ }
+ }
+ }
+
+ return (
+ <div className="tp-panel">
+ <div className="tp-tools">
+ {TOOLS.map((t) => (
+ <button
+ key={t.id}
+ type="button"
+ className={'tp-tool' + (tool === t.id ? ' is-active' : '')}
+ title={t.label}
+ onClick={() => setTool(tool === t.id ? null : t.id)}
+ >
+ <t.icon 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>
+ )}
+ </div>
+ </div>
+ );
+}
diff --git a/desktop/src/panels/Viewport.tsx b/desktop/src/panels/Viewport.tsx
index 77ace638a..7d8d1e640 100644
--- a/desktop/src/panels/Viewport.tsx
+++ b/desktop/src/panels/Viewport.tsx
@@ -19,6 +19,20 @@ import { SceneModel } from '@/engine/SceneModel';
import { SceneStore } from '@/engine/SceneStore';
import { StatsStore } from '@/engine/StatsStore';
import type { ToolMode } from '@/types';
+import { TilemapAPI } from 'esengine';
+import { useTilemapPaint, type PaintTool } from '@/store/tilemapPaintStore';
+import type { TilePaint } from '@/engine/SceneCommands';
+
+// Cursor (client px) → tile grid coords on a TilemapLayer entity: client→world via the
+// editor camera, then world→tile around the layer's world origin (its Transform).
+function cursorTile(clientX: number, clientY: number, sourceId: number): { x: number; y: number } | null {
+ const rt = SceneModel.runtimeFor(sourceId);
+ const wp = ViewportController.canvasToWorld(clientX, clientY);
+ const ep = rt != null ? ViewportController.getEntityXY(rt) : null;
+ if (rt == null || !wp || !ep) return null;
+ const t = TilemapAPI.worldToTile(rt, wp.x, wp.y, ep.x, ep.y);
+ return { x: Math.floor(t.x), y: Math.floor(t.y) };
+}
// Visual manipulation glyph, centered on the selected entity, reflecting the
// active tool. The drag itself (below) now applies move / rotate / scale.
@@ -214,6 +228,8 @@ export function Viewport() {
const gizmoRef = useRef<HTMLDivElement>(null);
const selectionRef = useRef<HTMLDivElement>(null);
const dragRef = useRef<Drag | null>(null);
+ // Active tilemap paint stroke (kept separate from the transform drag union above).
+ const paintRef = useRef<{ sourceId: number; tool: PaintTool; last: string; startX?: number; startY?: number } | null>(null);
const [zoomPct, setZoomPct] = useState(100);
const engine = useSyncExternalStore(EngineHost.subscribe, EngineHost.getSnapshot);
const realm = useSyncExternalStore(PlayRealm.subscribe, PlayRealm.getSnapshot);
@@ -342,6 +358,36 @@ export function Viewport() {
}
if (e.button !== 0) return;
+ // Tile painting: when a paint tool is active over the SELECTED TilemapLayer, the
+ // left button paints (it must NOT re-pick/select another entity).
+ const paint = useTilemapPaint.getState();
+ const selId = useSelection.getState().selectedId;
+ const isTilemap = selId != null
+ && !!SceneModel.entityBySource(selId)?.components.some((c) => c.type === 'TilemapLayer');
+ if (paint.tool && isTilemap && selId != null) {
+ e.preventDefault();
+ const tile = cursorTile(e.clientX, e.clientY, selId);
+ if (!tile) return;
+ if (paint.tool === 'eyedropper') {
+ const rt = SceneModel.runtimeFor(selId);
+ const id = rt != null ? TilemapAPI.getTile(rt, tile.x, tile.y) : 0;
+ if (id > 0) paint.setBrush(id);
+ return;
+ }
+ if (paint.tool === 'rect') {
+ paintRef.current = { sourceId: selId, tool: 'rect', last: '', startX: tile.x, startY: tile.y };
+ stageRef.current?.setPointerCapture(e.pointerId);
+ return;
+ }
+ // brush / erase — a live stroke committed as one undo step on release.
+ const tileId = paint.tool === 'erase' ? 0 : paint.brushTileId;
+ SceneCommands.beginTilePaint(selId);
+ SceneCommands.paintTileLive(selId, tile.x, tile.y, tileId);
+ paintRef.current = { sourceId: selId, tool: paint.tool, last: `${tile.x},${tile.y}` };
+ stageRef.current?.setPointerCapture(e.pointerId);
+ return;
+ }
+
// Pick returns a runtime World entity (rendering domain); the editor selects
// and commands by stable source id. Resolve once: source id drives selection
// + SceneCommands; the runtime id drives ViewportController screen geometry.
@@ -385,6 +431,24 @@ export function Viewport() {
const onPointerMove = (e: ReactPointerEvent) => {
const wp = ViewportController.canvasToWorld(e.clientX, e.clientY);
if (wp) StatsStore.setCursor(wp.x, wp.y);
+
+ // Live brush/erase stroke: paint each newly-entered tile (rect previews on release).
+ const p = paintRef.current;
+ if (p) {
+ if (p.tool === 'brush' || p.tool === 'erase') {
+ const tile = cursorTile(e.clientX, e.clientY, p.sourceId);
+ if (tile) {
+ const key = `${tile.x},${tile.y}`;
+ if (key !== p.last) {
+ const tileId = p.tool === 'erase' ? 0 : useTilemapPaint.getState().brushTileId;
+ SceneCommands.paintTileLive(p.sourceId, tile.x, tile.y, tileId);
+ p.last = key;
+ }
+ }
+ }
+ return; // painting overrides transform drag
+ }
+
const drag = dragRef.current;
if (!drag) return;
const snapOn = useEditorStore.getState().snapping;
@@ -422,6 +486,27 @@ export function Viewport() {
};
const endDrag = (e: ReactPointerEvent) => {
+ // Commit an in-progress tile paint stroke first.
+ const p = paintRef.current;
+ if (p) {
+ stageRef.current?.releasePointerCapture(e.pointerId);
+ paintRef.current = null;
+ if (p.tool === 'rect' && p.startX != null && p.startY != null) {
+ const tile = cursorTile(e.clientX, e.clientY, p.sourceId);
+ if (tile) {
+ const x0 = Math.min(p.startX, tile.x), x1 = Math.max(p.startX, tile.x);
+ const y0 = Math.min(p.startY, tile.y), y1 = Math.max(p.startY, tile.y);
+ const tileId = useTilemapPaint.getState().brushTileId;
+ const edits: TilePaint[] = [];
+ for (let y = y0; y <= y1; y++) for (let x = x0; x <= x1; x++) edits.push({ x, y, tileId });
+ SceneCommands.paintTiles(p.sourceId, edits);
+ }
+ } else {
+ SceneCommands.endTilePaint();
+ }
+ return;
+ }
+
const drag = dragRef.current;
if (!drag) return;
stageRef.current?.releasePointerCapture(e.pointerId);
diff --git a/desktop/src/store/tilemapPaintStore.ts b/desktop/src/store/tilemapPaintStore.ts
new file mode 100644
index 000000000..92b25c76c
--- /dev/null
+++ b/desktop/src/store/tilemapPaintStore.ts
@@ -0,0 +1,33 @@
+// SPDX-License-Identifier: LicenseRef-PolyForm-Noncommercial-1.0.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file tilemapPaintStore.ts
+ * @brief Transient tilemap-painting state (REARCH_TILEMAP T3b): 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
+ * selecting. Editor-session state — never serialized.
+ */
+import { create } from 'zustand';
+
+export type PaintTool = 'brush' | 'erase' | 'rect' | 'eyedropper';
+
+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;
+}
+
+export const useTilemapPaint = create<TilemapPaintState>((set) => ({
+ tilesetPath: null,
+ brushTileId: 1,
+ tool: null,
+ setTileset: (tilesetPath) => set({ tilesetPath }),
+ setBrush: (brushTileId) => set({ brushTileId }),
+ setTool: (tool) => set({ tool }),
+}));
diff --git a/desktop/src/theme/tilemap.css b/desktop/src/theme/tilemap.css
new file mode 100644
index 000000000..99ebd20b3
--- /dev/null
+++ b/desktop/src/theme/tilemap.css
@@ -0,0 +1,79 @@
+/* SPDX-License-Identifier: LicenseRef-PolyForm-Noncommercial-1.0.0 */
+/* SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team */
+/* The Tilemap painter panel (docs/REARCH_TILEMAP.md T3b). */
+
+.tp-panel {
+ display: flex;
+ flex-direction: column;
+ height: 100%;
+ background: var(--srf-1, #16181c);
+ color: var(--text, #d6d9de);
+ font-size: 12px;
+}
+
+.tp-tools {
+ display: flex;
+ align-items: center;
+ gap: 4px;
+ padding: 6px 10px;
+ border-bottom: 1px solid var(--line, #2a2d33);
+ background: var(--srf-2, #1b1e23);
+ flex: 0 0 auto;
+}
+.tp-grow { flex: 1 1 auto; }
+.tp-brush { color: var(--text-faint, #6b717c); font-variant-numeric: tabular-nums; }
+
+.tp-tool {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ width: 28px;
+ height: 26px;
+ background: var(--control, #24272d);
+ border: 1px solid var(--line, #2a2d33);
+ border-radius: 3px;
+ color: var(--text-dim, #9aa0aa);
+ cursor: pointer;
+}
+.tp-tool:hover { color: var(--text, #d6d9de); border-color: var(--control-hover, #333740); }
+.tp-tool.is-active {
+ background: var(--star, #4c8fd6);
+ border-color: var(--star, #4c8fd6);
+ color: var(--on-accent, #fff);
+}
+
+.tp-palette {
+ flex: 1 1 auto;
+ overflow: auto;
+ padding: 12px;
+ background: var(--srf-0, #101216);
+}
+.tp-atlas { position: relative; }
+.tp-img { display: block; image-rendering: pixelated; user-select: none; }
+
+.tp-cell {
+ position: absolute;
+ box-sizing: border-box;
+ border: 1px solid transparent;
+ cursor: pointer;
+}
+.tp-cell:hover { border-color: rgba(76, 143, 214, 0.6); background: rgba(76, 143, 214, 0.14); }
+.tp-cell.is-sel {
+ border-color: var(--star, #4c8fd6);
+ box-shadow: inset 0 0 0 1px var(--star, #4c8fd6);
+ background: rgba(76, 143, 214, 0.18);
+}
+
+.tp-empty,
+.tp-warn {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ justify-content: center;
+ height: 100%;
+ gap: 6px;
+ padding: 16px;
+ text-align: center;
+ color: var(--text-faint, #6b717c);
+}
+.tp-hint { font-size: 11px; max-width: 280px; }
diff --git a/desktop/src/tilemap/createTilemap.ts b/desktop/src/tilemap/createTilemap.ts
new file mode 100644
index 000000000..8bf7a738f
--- /dev/null
+++ b/desktop/src/tilemap/createTilemap.ts
@@ -0,0 +1,55 @@
+// SPDX-License-Identifier: LicenseRef-PolyForm-Noncommercial-1.0.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file createTilemap.ts
+ * @brief Spawn a scene-embedded TilemapLayer entity from an .estileset
+ * (REARCH_TILEMAP T3b) — the Unity/Godot model: the tilemap is a real,
+ * paintable entity, the tileset is the reusable asset it references.
+ */
+
+import { parseTileset } from 'esengine';
+import { SceneCommands } from '@/engine/SceneCommands';
+import { useSelection } from '@/store/selectionStore';
+import { useTilemapPaint } from '@/store/tilemapPaintStore';
+import { ProjectStore } from '@/project/ProjectStore';
+import { dockApi } from '@/layout/dockApi';
+import { Toasts } from '@/store/Toasts';
+
+/** Create a TilemapLayer entity referencing the given .estileset, select it, and start painting. */
+export async function createTilemapFromTileset(tilesetPath: string): Promise<void> {
+ const tilesetRef = ProjectStore.assetRef(tilesetPath); // .estileset → @uuid
+ if (!tilesetRef) {
+ Toasts.push('该瓦片集未被项目追踪', 'error');
+ return;
+ }
+ let asset;
+ try {
+ asset = parseTileset(JSON.parse(await window.estella.fs.read(tilesetPath)));
+ } catch (e) {
+ Toasts.push(`读取瓦片集失败:${String(e)}`, 'error');
+ return;
+ }
+
+ // Preload the atlas texture so the Reconciler resolves its handle and the
+ // TilemapSyncSystem (which needs a non-zero texture + dims) initializes the layer.
+ const texInfo = ProjectStore.assetInfo(asset.texture);
+ if (texInfo) await ProjectStore.assetRefForPath(texInfo.path, 'texture');
+
+ const sourceId = SceneCommands.addEntity();
+ if (sourceId == null) return;
+ SceneCommands.addComponent(sourceId, 'TilemapLayer');
+ SceneCommands.beginGesture('Configure Tilemap');
+ SceneCommands.setField(sourceId, 'TilemapLayer', 'cellSize', 'vec2', [asset.tileWidth, asset.tileHeight]);
+ SceneCommands.setField(sourceId, 'TilemapLayer', 'tileset', 'string', asset.texture); // texture @uuid → handle
+ SceneCommands.setField(sourceId, 'TilemapLayer', 'tilesetColumns', 'number', asset.columns);
+ // The .estileset link (editor palette restore + T4 runtime collision). Not a C++
+ // field — carried losslessly in the model like the chunks blob.
+ SceneCommands.setField(sourceId, 'TilemapLayer', 'tilesetAsset', 'string', tilesetRef);
+ SceneCommands.endGesture();
+
+ useSelection.getState().select(sourceId);
+ useTilemapPaint.getState().setTileset(tilesetPath);
+ useTilemapPaint.getState().setTool('brush');
+ dockApi.revealAndExpand('tilemap');
+ Toasts.push('已创建瓦片地图 — 选择刷子在视口绘制', 'info');
+}
diff --git a/desktop/tests/paint-tiles.test.ts b/desktop/tests/paint-tiles.test.ts
index b50cd1c75..a674dbdcd 100644
--- a/desktop/tests/paint-tiles.test.ts
+++ b/desktop/tests/paint-tiles.test.ts
@@ -84,4 +84,21 @@ describe('SceneCommands.paintTiles', () => {
cmds.paintTiles(1, [{ x: 0, y: 0, tileId: 1 }]);
expect(history.canUndo()).toBe(false);
});
+
+ it('begin/live/end paints a stroke live and commits one undo step', () => {
+ const setTile = vi.spyOn(TilemapAPI, 'setTile').mockImplementation(() => {});
+ const importChunks = vi.spyOn(TilemapAPI, 'importChunks').mockReturnValue(true);
+ vi.spyOn(TilemapAPI, 'exportChunks')
+ .mockReturnValueOnce('B0') // begin snapshot
+ .mockReturnValueOnce('B1'); // end → commit after-snapshot
+ cmds.beginTilePaint(1);
+ cmds.paintTileLive(1, 0, 0, 7);
+ cmds.paintTileLive(1, 1, 0, 7);
+ cmds.endTilePaint();
+ expect(setTile).toHaveBeenCalledTimes(2);
+ expect(chunksOf(model)).toBe('B1');
+ history.undo();
+ expect(importChunks).toHaveBeenLastCalledWith(100, 'B0');
+ expect(chunksOf(model)).toBe('B0');
+ });
});