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(tilemap): modernize the painter interaction (unified tile-editing mode)

esengine7ca64724e5b5
diff --git a/desktop/src/App.tsx b/desktop/src/App.tsx
index df8957782..4b9b719d4 100644
--- a/desktop/src/App.tsx
+++ b/desktop/src/App.tsx
@@ -17,6 +17,8 @@ import { SettingsDialog } from '@/components/SettingsDialog';
import { TilemapPickerDialog } from '@/components/TilemapPickerDialog';
import { useEditorStore } from '@/store/editorStore';
import { commands } from '@/commands';
+import { handleTilePaintKey, isTilemapSelected } from '@/tools/tileMode';
+import { useSelection } from '@/store/selectionStore';
import { PlayRealms } from '@/engine/PlayRealm';
import { PlayInspect } from '@/engine/PlayInspect';
import { TimelinePreview } from '@/engine/TimelinePreview';
@@ -44,6 +46,12 @@ export function App() {
if (el && (el.tagName === 'INPUT' || el.tagName === 'TEXTAREA' || el.isContentEditable)) {
return;
}
+ // Tile-editing context claims its keys first (single dispatch → no double-fire
+ // with the transform-tool command bound to the same letter).
+ if (handleTilePaintKey(e)) {
+ e.preventDefault();
+ return;
+ }
const cmd = commands.forEvent(e);
if (cmd) {
e.preventDefault();
@@ -54,6 +62,18 @@ export function App() {
return () => window.removeEventListener('keydown', onKey);
}, []);
+ // Surface the Tilemap painter when a tilemap entity becomes the selection (only on
+ // the transition INTO one, so switching between tilemaps doesn't keep yanking focus).
+ // "Select a tilemap → here's how you paint it" then needs no hunting for the panel.
+ useEffect(() => {
+ let wasTilemap = false;
+ return useSelection.subscribe(() => {
+ const isTm = isTilemapSelected();
+ if (isTm && !wasTilemap) dockApi.openSidePanel('tilemap', 'tilemap', 'Tilemap', 'left', 300);
+ wasTilemap = isTm;
+ });
+ }, []);
+
// Wire the Sequencer's edit-mode live preview (timeline document → World) and
// record-mode auto-key once.
useEffect(() => {
diff --git a/desktop/src/engine/StatsStore.ts b/desktop/src/engine/StatsStore.ts
index 3ac23c6a5..7b5bba8ff 100644
--- a/desktop/src/engine/StatsStore.ts
+++ b/desktop/src/engine/StatsStore.ts
@@ -69,6 +69,8 @@ class StatsStoreImpl {
private readonly store = createStore<StatsSnapshot>(() => ({ fps: 0, entities: 0, selection: null, vram: null }));
// Pointer-rate churn stays out of the slow-stats subscribers.
private readonly cursorStore = createStore<{ x: number; y: number } | null>(() => null);
+ // The hovered tile cell (coords + id) while painting a tilemap, or null.
+ private readonly tileStore = createStore<{ tx: number; ty: number; id: number } | null>(() => null);
private running = false;
private frames = 0;
@@ -114,10 +116,23 @@ class StatsStoreImpl {
if (this.cursorStore.getState()) this.cursorStore.setState(null, true);
}
+ /** Report the hovered tile cell (tilemap paint), ignoring no-op moves. */
+ setTile(tx: number, ty: number, id: number) {
+ const cur = this.tileStore.getState();
+ if (cur && cur.tx === tx && cur.ty === ty && cur.id === id) return;
+ this.tileStore.setState({ tx, ty, id }, true);
+ }
+
+ clearTile() {
+ if (this.tileStore.getState()) this.tileStore.setState(null, true);
+ }
+
subscribe = (fn: () => void): (() => void) => this.store.subscribe(fn);
getSnapshot = (): StatsSnapshot => this.store.getState();
subscribeCursor = (fn: () => void): (() => void) => this.cursorStore.subscribe(fn);
getCursor = (): { x: number; y: number } | null => this.cursorStore.getState();
+ subscribeTile = (fn: () => void): (() => void) => this.tileStore.subscribe(fn);
+ getTile = (): { tx: number; ty: number; id: number } | null => this.tileStore.getState();
}
export const StatsStore = new StatsStoreImpl();
diff --git a/desktop/src/panels/TilemapPainter.tsx b/desktop/src/panels/TilemapPainter.tsx
index 417416195..a45a7b7cb 100644
--- a/desktop/src/panels/TilemapPainter.tsx
+++ b/desktop/src/panels/TilemapPainter.tsx
@@ -12,15 +12,17 @@
import { useEffect, useRef, useState } from 'react';
import {
Brush, Eraser, Square, Slash, PaintBucket, BoxSelect, Pipette,
- FlipHorizontal, FlipVertical, RotateCw, Mountain, Plus, X,
+ FlipHorizontal, FlipVertical, RotateCw, Mountain, Plus, X, MousePointer2,
+ ZoomIn, ZoomOut, Maximize2, Eye, EyeOff, Lock, Unlock,
} from 'lucide-react';
-import { parseTileset, encodeTile, type TilesetAsset } from 'esengine';
-import { useTilemapPaint, type PaintTool, type PaletteTileset } from '@/store/tilemapPaintStore';
+import { parseTileset, encodeTile, type TilesetAsset, type TileStamp } from 'esengine';
+import { useTilemapPaint, type PaintTool, type PaletteTileset, type AtlasInfo } from '@/store/tilemapPaintStore';
import { useSelection } from '@/store/selectionStore';
import { SceneModel } from '@/engine/SceneModel';
import { SceneCommands } from '@/engine/SceneCommands';
import { ProjectStore } from '@/project/ProjectStore';
-import { copySelection, cutSelection, deleteSelection, pasteClipboard } from '@/tools/tileClipboard';
+import { TILE_TOOL_KEY, exitTilePaint } from '@/tools/tileMode';
+import { buildStampGhost } from '@/tools/tileStampGhost';
function colsFor(width: number, tileW: number, margin: number, spacing: number): number {
const stride = tileW + spacing;
@@ -72,10 +74,32 @@ const normRect = (a: { c: number; r: number }, b: { c: number; r: number }): Sel
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),
});
+const clamp = (n: number, lo: number, hi: number): number => Math.max(lo, Math.min(hi, n));
+
+/** A tiny live preview of the active brush (the real tiles + their flip/rotate), so the
+ * toolbar shows WHAT you'll paint, not just its dimensions. Reuses the viewport ghost
+ * geometry. */
+function BrushThumbnail({ stamp, atlas }: { stamp: TileStamp; atlas: AtlasInfo | null }) {
+ const cells = buildStampGhost(stamp, atlas);
+ if (!cells || !atlas) return null;
+ const natW = stamp.w * atlas.tileW;
+ const natH = stamp.h * atlas.tileH;
+ const MAX = 26;
+ const scale = Math.min(MAX / natW, MAX / natH);
+ return (
+ <span className="tp-brushthumb" style={{ width: natW * scale, height: natH * scale }}>
+ <span className="tp-brushthumb-in" style={{ width: natW, height: natH, transform: `scale(${scale})` }}>
+ {cells.map((c, i) => <span key={i} style={c.style} />)}
+ </span>
+ </span>
+ );
+}
+
export function TilemapPainter() {
const {
tilesetPath, tilesets, activeTileset, stamp, tool, terrainSet,
- setTilesets, setActiveTileset, setTilesetAsset, setStamp, setTool, setTerrainSet, flipH, flipV, rotateCW,
+ setTilesets, setActiveTileset, setTilesetAsset, setStamp, setTool, setTerrainSet,
+ setActiveAtlas, flipH, flipV, rotateCW,
} = useTilemapPaint();
const selectedId = useSelection((s) => s.selectedId);
const hasTilemap = selectedId != null
@@ -131,35 +155,40 @@ export function TilemapPainter() {
const [natural, setNatural] = useState<{ w: number; h: number } | null>(null);
useEffect(() => setNatural(null), [texUrl]);
+ // Publish the active tileset's atlas layout for the viewport's WYSIWYG brush ghost.
+ // The painter is the one place that loads the atlas image, so it owns this geometry;
+ // the viewport reads it instead of re-loading. Cleared on unmount so a closed painter
+ // leaves no stale ghost.
+ useEffect(() => {
+ if (!asset || !natural || !texUrl) { setActiveAtlas(null); return; }
+ setActiveAtlas({
+ url: texUrl,
+ cols: colsFor(natural.w, asset.tileWidth, asset.margin, asset.spacing),
+ tileW: asset.tileWidth, tileH: asset.tileHeight,
+ margin: asset.margin, spacing: asset.spacing,
+ firstId: tilesets[activeTileset]?.firstId ?? 1,
+ });
+ }, [asset, natural, texUrl, tilesets, activeTileset, setActiveAtlas]);
+ useEffect(() => () => setActiveAtlas(null), [setActiveAtlas]);
+
// 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);
- // Paint-mode keys (only while a paint tool is active, so they don't shadow the
- // transform-tool shortcuts): select-tool clipboard (⌘/Ctrl C/X/V, Delete) and the
- // stamp transforms H/V/R.
+ // Palette zoom (small tilesets are unclickable at 1:1). A fresh tileset opens at a
+ // comfortable magnification derived from its tile size; − / + / fit adjust from there.
+ const paletteRef = useRef<HTMLDivElement>(null);
+ const [zoom, setZoom] = useState(2);
useEffect(() => {
- const onKey = (e: KeyboardEvent) => {
- const st = useTilemapPaint.getState();
- if (!st.tool) return;
- const t = e.target as HTMLElement | null;
- if (t && (t.tagName === 'INPUT' || t.tagName === 'TEXTAREA' || t.isContentEditable)) return;
- const mod = e.metaKey || e.ctrlKey;
- const k = e.key.toLowerCase();
- if (st.tool === 'select') {
- if (mod && k === 'c') { copySelection(); e.preventDefault(); return; }
- if (mod && k === 'x') { cutSelection(); e.preventDefault(); return; }
- if (e.key === 'Delete' || e.key === 'Backspace') { deleteSelection(); e.preventDefault(); return; }
- }
- if (mod && k === 'v') { pasteClipboard(); e.preventDefault(); return; }
- if (mod || e.altKey) return;
- 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 (asset) setZoom(clamp(Math.round(28 / (asset.tileWidth || 16)), 1, 4));
+ }, [tilesetPath, asset]);
+ // Clearing the marquee when the active tileset changes stops a stale highlight from
+ // lingering on a tab that no longer shows the picked cells.
+ useEffect(() => setSel(null), [activeTileset]);
+ const fitZoom = () => {
+ const pal = paletteRef.current;
+ if (pal && natural && natural.w > 0) setZoom(clamp((pal.clientWidth - 16) / natural.w, 0.25, 8));
+ };
// Dismiss the add-tileset menu on any outside click (the menu + its opener stop
// their own pointerdown so those don't self-close it).
@@ -170,6 +199,10 @@ export function TilemapPainter() {
return () => window.removeEventListener('pointerdown', close);
}, [addOpen]);
+ // Re-render the layer strip on any model change (add/remove/rename/hide/lock).
+ const [, bumpModel] = useState(0);
+ useEffect(() => SceneModel.subscribe(() => bumpModel((v) => v + 1)), []);
+
if (!hasTilemap) {
return (
<div className="tp-empty">
@@ -188,6 +221,16 @@ export function TilemapPainter() {
// Global tile-id base of the active tileset — a cell's gid = firstId + (row*cols + col),
// so the renderer resolves it back to THIS tileset (single-tileset layers have firstId 1).
const activeFirstId = tilesets[activeTileset]?.firstId ?? 1;
+ const localAtlas: AtlasInfo | null = texUrl && natural
+ ? { url: texUrl, cols, tileW: tw, tileH: th, margin: mg, spacing: sp, firstId: activeFirstId }
+ : null;
+
+ // The scene's tilemap layers (the paint targets) — click one to make it active, without
+ // hunting in the Outliner; toggle its viewport visibility / lock inline.
+ const layers = SceneModel.entityOrder()
+ .map((id) => ({ id, e: SceneModel.entityBySource(id) }))
+ .filter((L) => L.e?.components.some((c) => c.type === 'TilemapLayer'))
+ .map((L) => ({ id: L.id, name: L.e!.name, hidden: SceneModel.isHidden(L.id), locked: SceneModel.isLocked(L.id) }));
const commitSel = (r: SelRect) => {
const w = r.c1 - r.c0 + 1;
@@ -255,14 +298,49 @@ export function TilemapPainter() {
return (
<div className="tp-panel">
+ {layers.length > 1 && (
+ <div className="tp-layers">
+ {layers.map((L) => (
+ <span key={L.id} className={'tp-layer' + (L.id === selectedId ? ' is-active' : '')}>
+ <button
+ type="button" className="tp-layer-vis" title={L.hidden ? '显示' : '隐藏'}
+ onClick={() => SceneCommands.setEntityVisible(L.id, L.hidden)}
+ >
+ {L.hidden ? <EyeOff size={12} /> : <Eye size={12} />}
+ </button>
+ <button
+ type="button" className="tp-layer-name" title={`绘制到「${L.name}」`}
+ onClick={() => useSelection.getState().select(L.id)}
+ >
+ {L.name}
+ </button>
+ <button
+ type="button" className="tp-layer-lock" title={L.locked ? '解锁' : '锁定'}
+ onClick={() => SceneCommands.setEntityLocked(L.id, !L.locked)}
+ >
+ {L.locked ? <Lock size={11} /> : <Unlock size={11} />}
+ </button>
+ </span>
+ ))}
+ </div>
+ )}
<div className="tp-tools">
+ <button
+ type="button"
+ className={'tp-tool' + (tool === null ? ' is-active' : '')}
+ title="选择 / 变换 (Q · Esc 退出绘制)"
+ onClick={() => exitTilePaint('select')}
+ >
+ <MousePointer2 size={15} />
+ </button>
+ <span className="tp-sep" />
{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)}
+ title={`${t.label} (${TILE_TOOL_KEY[t.id]})`}
+ onClick={() => setTool(t.id)}
>
<t.icon size={15} />
</button>
@@ -278,7 +356,14 @@ export function TilemapPainter() {
<RotateCw size={15} />
</button>
<span className="tp-grow" />
- <span className="tp-brush">{tool === 'terrain' ? '地形画笔' : `刷子 ${stamp.w}×${stamp.h}`}</span>
+ <span className="tp-brush">
+ {tool === 'terrain' ? '地形画笔' : (
+ <>
+ <BrushThumbnail stamp={stamp} atlas={localAtlas} />
+ {stamp.w}×{stamp.h}
+ </>
+ )}
+ </span>
</div>
{tool !== 'terrain' && (
<div className="tp-tilesets">
@@ -337,19 +422,40 @@ export function TilemapPainter() {
)}
</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}
+ <>
+ {texUrl && (
+ <div className="tp-palbar">
+ <button type="button" className="tp-zbtn" title="缩小" onClick={() => setZoom((z) => clamp(z / 1.25, 0.25, 8))}>
+ <ZoomOut size={13} />
+ </button>
+ <span className="tp-zpct">{Math.round(zoom * 100)}%</span>
+ <button type="button" className="tp-zbtn" title="放大" onClick={() => setZoom((z) => clamp(z * 1.25, 0.25, 8))}>
+ <ZoomIn size={13} />
+ </button>
+ <button type="button" className="tp-zbtn" title="适应宽度" onClick={fitZoom}>
+ <Maximize2 size={13} />
+ </button>
</div>
)}
- </div>
+ <div className="tp-palette" ref={paletteRef} onPointerUp={endDrag} onPointerLeave={endDrag}>
+ {!texUrl ? (
+ <div className="tp-warn">没有调色板(瓦片地图未引用 .estileset)</div>
+ ) : (
+ <div className="tp-atlas-sizer" style={{ width: (natural?.w ?? 0) * zoom, height: (natural?.h ?? 0) * zoom }}>
+ <div
+ className="tp-atlas"
+ style={{ width: natural?.w ?? 0, height: natural?.h ?? 0, transform: `scale(${zoom})`, transformOrigin: '0 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>
+ </>
)}
</div>
);
diff --git a/desktop/src/panels/Viewport.tsx b/desktop/src/panels/Viewport.tsx
index 438f8a013..c308251a1 100644
--- a/desktop/src/panels/Viewport.tsx
+++ b/desktop/src/panels/Viewport.tsx
@@ -8,7 +8,10 @@ import {
} from 'lucide-react';
import { useEditorStore } from '@/store/editorStore';
import { useSelection } from '@/store/selectionStore';
-import { useTilemapPaint } from '@/store/tilemapPaintStore';
+import { useTilemapPaint, type PaintTool } from '@/store/tilemapPaintStore';
+import { exitTilePaint, isTilePaintMode, selectedTilemapCellSize } from '@/tools/tileMode';
+import { buildStampGhost } from '@/tools/tileStampGhost';
+import { TilemapAPI, tileIdOf } from 'esengine';
import { commands } from '@/commands';
import { EngineHost } from '@/engine/EngineHost';
import { PlayRealm } from '@/engine/PlayRealm';
@@ -205,6 +208,25 @@ const TOOL_HINT: Record<ToolMode, string> = {
scale: 'Drag a handle for per-axis scale · center for uniform',
};
+// Hint shown while painting a tilemap — replaces TOOL_HINT so the viewport speaks the
+// paint vocabulary (and always points at Q/Esc as the way back to select/transform).
+const TILE_HINT: Record<PaintTool, string> = {
+ brush: '拖动绘制 · H/V 翻转 · R 旋转笔刷 · I 吸管 · Q/Esc 退出',
+ erase: '拖动擦除(按笔刷大小) · Q/Esc 退出',
+ rect: '拖出矩形填充 · Q/Esc 退出',
+ line: '拖出直线 · Q/Esc 退出',
+ bucket: '点击油漆桶填充连通区域 · Q/Esc 退出',
+ select: '框选 · ⌘C/X 复制/剪切 · Del 清除 · ⌘V 粘贴为笔刷 · Q/Esc 退出',
+ eyedropper: '点击拾取瓦片到笔刷 · Q/Esc 退出',
+ terrain: '拖动绘制地形(自动过渡) · Q/Esc 退出',
+};
+
+// Label for the mode badge — the paint tool's short name.
+const TILE_TOOL_LABEL: Record<PaintTool, string> = {
+ brush: '画笔', erase: '擦除', rect: '矩形', line: '直线',
+ bucket: '油漆桶', select: '选区', eyedropper: '吸管', terrain: '地形',
+};
+
function OvTool({
icon: Icon,
label,
@@ -304,12 +326,16 @@ function DdRadio({ on, label, onClick }: { on: boolean; label: string; onClick:
// Only this node re-renders per mouse move; the HUD follows the slow stats cadence.
function HudCursor() {
const cursor = useSyncExternalStore(StatsStore.subscribeCursor, StatsStore.getCursor);
- if (!cursor) return null;
+ const tile = useSyncExternalStore(StatsStore.subscribeTile, StatsStore.getTile);
+ if (!cursor && !tile) return null;
return (
<>
- <strong>
- {cursor.x}, {cursor.y}
- </strong>{' '}
+ {cursor && <strong>{cursor.x}, {cursor.y}</strong>}
+ {tile && (
+ <span className="hud-tile">
+ {' '}▦ {tile.tx}, {tile.ty}{tile.id ? ` #${tile.id}` : ''}
+ </span>
+ )}{' '}
·{' '}
</>
);
@@ -318,11 +344,13 @@ function HudCursor() {
// The corner HUD (perf + coordinates). Owns the StatsStore subscription so the
// slow stats updates re-render ONLY this leaf — not the whole, gizmo-heavy
// Viewport.
-function ViewportHud({ ready, selCount, zoomPct, tool }: {
+function ViewportHud({ ready, selCount, zoomPct, tool, paintHint }: {
ready: boolean;
selCount: number;
zoomPct: number;
tool: ToolMode;
+ /** When painting a tilemap, the tile-vocabulary hint replaces the transform hint. */
+ paintHint: string | null;
}) {
const stats = useSyncExternalStore(StatsStore.subscribe, StatsStore.getSnapshot);
return (
@@ -349,7 +377,7 @@ function ViewportHud({ ready, selCount, zoomPct, tool }: {
<HudCursor />
Sel <strong>{selCount}</strong> · {zoomPct}%
</div>
- <div className="hint">{TOOL_HINT[tool]}</div>
+ <div className="hint">{paintHint ?? TOOL_HINT[tool]}</div>
</div>
</>
);
@@ -375,6 +403,21 @@ export function Viewport() {
const selectedIds = useSelection((s) => s.selectedIds);
const primaryId = useSelection((s) => s.selectedId);
const selList = useMemo(() => [...selectedIds], [selectedIds]);
+ // Tile-editing context: a paint tool active over a selected TilemapLayer. Drives the
+ // viewport mode badge, the HUD hint, and the tile-sized reference grid.
+ const paintTool = useTilemapPaint((s) => s.tool);
+ const tilemapSelected = primaryId != null
+ && !!SceneModel.entityBySource(primaryId)?.components.some((c) => c.type === 'TilemapLayer');
+ const inTilePaint = paintTool != null && tilemapSelected;
+ // WYSIWYG brush ghost: the actual stamp tiles, built once per stamp/atlas change and
+ // laid out at natural tile pixels; the rAF scales the container to the hovered
+ // footprint each frame (see the tile-preview block). Empty (null) → the plain box shows.
+ const stamp = useTilemapPaint((s) => s.stamp);
+ const activeAtlas = useTilemapPaint((s) => s.activeAtlas);
+ const ghostCells = useMemo(() => buildStampGhost(stamp, activeAtlas), [stamp, activeAtlas]);
+ const ghostNat = ghostCells && activeAtlas
+ ? { w: stamp.w * activeAtlas.tileW, h: stamp.h * activeAtlas.tileH }
+ : null;
const stageRef = useRef<HTMLDivElement>(null);
const playHostRef = useRef<HTMLDivElement>(null);
@@ -384,6 +427,7 @@ export function Viewport() {
const marqueeRef = useRef<HTMLDivElement>(null);
const tileSelRef = useRef<HTMLDivElement>(null);
const tilePreviewRef = useRef<HTMLDivElement>(null);
+ const tileGhostRef = useRef<HTMLDivElement>(null);
// Gesture-paint preview (rect fill / line cells): a container whose ghost-cell
// children are pooled + positioned imperatively in the rAF (rect/line defer their
// commit to release, so this shows the shape mid-drag).
@@ -451,10 +495,15 @@ export function Viewport() {
// Drive the engine's world-space editor grid from Show-Flags (Grid) + Snap
// step. Re-applied when the engine becomes ready, since the grid resource
// exists only after boot. Play/edit gating lives in the renderer (EditorView).
+ // While a tilemap is selected the grid matches its cell size (not the transform
+ // snap step) so the lines read as the tile grid you're painting on. (The grid is
+ // world-origin-anchored; a non-origin tilemap won't perfectly register until the
+ // origin-offset support lands.)
useEffect(() => {
if (engine.status !== 'ready') return;
- EngineHost.setGrid(showGrid, snapStep);
- }, [showGrid, snapStep, engine.status]);
+ const cell = selectedTilemapCellSize();
+ EngineHost.setGrid(showGrid, cell ? cell.x : snapStep);
+ }, [showGrid, snapStep, primaryId, engine.status]);
// Play In Viewport (UE5 PIE): host the realm iframe over the stage while playing
// here; App.start() already booted the realm — we just re-parent its iframe.
@@ -570,31 +619,47 @@ export function Viewport() {
ts.style.opacity = '0';
}
- // Brush footprint preview: a ghost rect at the hovered tile. brush/erase size it
- // to the active stamp (they lay/erase its w×h); the other tools mark a single
- // cell. Hidden for rect/line while their gesture preview is drawing the shape.
+ // Hover preview at the cursor cell. The BRUSH shows a WYSIWYG ghost of the actual
+ // stamp tiles (viewport__tileghost — built in React, scaled to the footprint here);
+ // erase sizes the plain box to the stamp; the other tools mark a single cell.
+ // Hidden for rect/line while their gesture preview draws the shape.
const dragging = TilePaintPreview.get() != null;
+ const hov = hoverTileRef.current;
+ const gesturing = dragging && (paint.tool === 'rect' || paint.tool === 'line');
+ const stampSized = paint.tool === 'brush' || paint.tool === 'erase';
+ const canFoot = !!(paint.tool && !gesturing && hov && cs?.cellSize && origin);
+ // Footprint corners in client px (fw×fh cells at the hovered cell).
+ let ftl: { x: number; y: number } | null = null;
+ let fbr: { x: number; y: number } | null = null;
+ if (canFoot && hov && cs?.cellSize && origin) {
+ const fw = stampSized ? paint.stamp.w : 1;
+ const fh = stampSized ? paint.stamp.h : 1;
+ ftl = ViewportController.worldToClient(origin.x + hov.x * cs.cellSize.x, origin.y - hov.y * cs.cellSize.y);
+ fbr = ViewportController.worldToClient(origin.x + (hov.x + fw) * cs.cellSize.x, origin.y - (hov.y + fh) * cs.cellSize.y);
+ }
+
+ const gh = tileGhostRef.current;
+ // Brush + a resolved ghost → the WYSIWYG tile preview owns the hover; else the box.
+ const useGhost = paint.tool === 'brush' && !!paint.activeAtlas
+ && !!gh && gh.childElementCount > 0;
+ if (gh) {
+ if (useGhost && ftl && fbr && paint.activeAtlas) {
+ const natW = paint.stamp.w * paint.activeAtlas.tileW;
+ const natH = paint.stamp.h * paint.activeAtlas.tileH;
+ gh.style.transform =
+ `translate(${ftl.x}px, ${ftl.y}px) scale(${(fbr.x - ftl.x) / natW}, ${(fbr.y - ftl.y) / natH})`;
+ gh.style.opacity = '1';
+ } else {
+ gh.style.opacity = '0';
+ }
+ }
const pv = tilePreviewRef.current;
if (pv) {
- const stampSized = paint.tool === 'brush' || paint.tool === 'erase';
- const SINGLE: Record<string, boolean> = { bucket: true, terrain: true, rect: true, line: true };
- const hov = hoverTileRef.current;
- const gesturing = dragging && (paint.tool === 'rect' || paint.tool === 'line');
- const showFoot = paint.tool != null && (stampSized || SINGLE[paint.tool])
- && !gesturing && hov && cs?.cellSize && origin;
- if (showFoot && hov && cs?.cellSize && origin) {
- const fw = stampSized ? paint.stamp.w : 1;
- const fh = stampSized ? paint.stamp.h : 1;
- const tl = ViewportController.worldToClient(origin.x + hov.x * cs.cellSize.x, origin.y - hov.y * cs.cellSize.y);
- const br = ViewportController.worldToClient(origin.x + (hov.x + fw) * cs.cellSize.x, origin.y - (hov.y + fh) * cs.cellSize.y);
- if (tl && br) {
- pv.style.transform = `translate(${tl.x}px, ${tl.y}px)`;
- pv.style.width = `${br.x - tl.x}px`;
- pv.style.height = `${br.y - tl.y}px`;
- pv.style.opacity = '1';
- } else {
- pv.style.opacity = '0';
- }
+ if (!useGhost && canFoot && ftl && fbr) {
+ pv.style.transform = `translate(${ftl.x}px, ${ftl.y}px)`;
+ pv.style.width = `${fbr.x - ftl.x}px`;
+ pv.style.height = `${fbr.y - ftl.y}px`;
+ pv.style.opacity = '1';
} else {
pv.style.opacity = '0';
}
@@ -822,9 +887,9 @@ export function Viewport() {
return () => cancelAnimationFrame(raf);
}, []);
- // Esc cancels an in-progress stroke (revert the live drag via the tool's
- // transaction) instead of deselecting. Capture phase so it pre-empts the global
- // Esc→deselect command; a no-op when no stroke is active (deselect then runs).
+ // Esc, capture phase (pre-empts the global Esc→deselect), in priority order:
+ // cancel an in-progress stroke → cancel a pan → leave paint mode → (fall through
+ // to deselect). So Esc reverts a live drag, then exits painting, then deselects.
useEffect(() => {
const onKey = (e: KeyboardEvent) => {
if (e.key !== 'Escape') return;
@@ -835,6 +900,9 @@ export function Viewport() {
} else if (panRef.current) {
panRef.current = null;
e.stopImmediatePropagation();
+ } else if (isTilePaintMode()) {
+ exitTilePaint();
+ e.stopImmediatePropagation();
}
};
window.addEventListener('keydown', onKey, true);
@@ -880,7 +948,16 @@ export function Viewport() {
const sid = useTilemapPaint.getState().tool ? useSelection.getState().selectedId : null;
const isTm = sid != null
&& !!SceneModel.entityBySource(sid)?.components.some((c) => c.type === 'TilemapLayer');
- hoverTileRef.current = sid != null && isTm ? cursorTile(e.clientX, e.clientY, sid) : null;
+ const tile = sid != null && isTm ? cursorTile(e.clientX, e.clientY, sid) : null;
+ hoverTileRef.current = tile;
+ // HUD tile readout: the hovered cell + its current id (0 = empty), so you always know
+ // exactly which cell you're about to paint.
+ if (tile && sid != null) {
+ const rt = SceneModel.runtimeFor(sid);
+ StatsStore.setTile(tile.x, tile.y, rt != null ? tileIdOf(TilemapAPI.getTile(rt, tile.x, tile.y)) : 0);
+ } else {
+ StatsStore.clearTile();
+ }
activeToolRef.current?.onPointerMove(toInput(e), toolCtx);
};
@@ -1035,7 +1112,7 @@ export function Viewport() {
onPointerMove={onPointerMove}
onPointerUp={endDrag}
onPointerCancel={cancelDrag}
- onPointerLeave={() => { StatsStore.clearCursor(); hoverTileRef.current = null; }}
+ onPointerLeave={() => { StatsStore.clearCursor(); StatsStore.clearTile(); hoverTileRef.current = null; }}
onContextMenu={(e) => e.preventDefault()}
onDragOver={onDragOver}
onDrop={onDrop}
@@ -1238,6 +1315,16 @@ export function Viewport() {
<div ref={marqueeRef} className="viewport__marquee" aria-hidden="true" />
<div ref={tileSelRef} className="viewport__tilesel" aria-hidden="true" />
<div ref={tilePreviewRef} className="viewport__tilepreview" aria-hidden="true" />
+ <div
+ ref={tileGhostRef}
+ className="viewport__tileghost"
+ aria-hidden="true"
+ style={ghostNat ? { width: ghostNat.w, height: ghostNat.h } : undefined}
+ >
+ {ghostCells?.map((c, i) => (
+ <div key={i} className="viewport__tileghost-cell" style={c.style} />
+ ))}
+ </div>
<div ref={tilePaintRef} className="viewport__tilepaint" aria-hidden="true" />
<div ref={gizmoRef} className="viewport__gizmo" aria-hidden="true">
@@ -1263,9 +1350,18 @@ export function Viewport() {
</div>
)}
- <ViewportHud ready={engine.status === 'ready'} selCount={selCount} zoomPct={zoomPct} tool={tool} />
+ <ViewportHud
+ ready={engine.status === 'ready'}
+ selCount={selCount}
+ zoomPct={zoomPct}
+ tool={tool}
+ paintHint={inTilePaint && paintTool ? TILE_HINT[paintTool] : null}
+ />
{perfVisible && <Perf id="viewport.perfhud"><PerfOverlay /></Perf>}
+ {inTilePaint && paintTool && (
+ <div className="viewport__tileflag">◧ 瓦片绘制 · {TILE_TOOL_LABEL[paintTool]}</div>
+ )}
{isPlaying && <div className="viewport__playflag">● PLAY</div>}
</div>
);
diff --git a/desktop/src/store/tilemapPaintStore.ts b/desktop/src/store/tilemapPaintStore.ts
index 648eb6dc3..2c7d3e1e5 100644
--- a/desktop/src/store/tilemapPaintStore.ts
+++ b/desktop/src/store/tilemapPaintStore.ts
@@ -33,6 +33,20 @@ export interface TileRect {
y1: number;
}
+/** The active tileset's on-screen atlas layout — the SINGLE source of atlas geometry,
+ * resolved once by the painter (which loads the image) and consumed by the viewport's
+ * WYSIWYG brush ghost, so the viewport never re-loads or re-measures the atlas. */
+export interface AtlasInfo {
+ url: string;
+ cols: number;
+ tileW: number;
+ tileH: number;
+ margin: number;
+ spacing: number;
+ /** Global tile-id base of this tileset (a cell's gid = firstId + row*cols + col). */
+ firstId: number;
+}
+
interface TilemapPaintState {
/** The active layer's tilesets, in firstId order (one entry = a single-tileset layer). */
tilesets: PaletteTileset[];
@@ -52,6 +66,8 @@ interface TilemapPaintState {
clipboard: TileStamp | null;
/** The active tool; null = not painting (the Viewport selects normally). */
tool: PaintTool | null;
+ /** The active tileset's atlas layout (for the viewport brush ghost), or null. */
+ activeAtlas: AtlasInfo | null;
/** Replace the active layer's palette list (from its tilesetAssets); resets active to 0. */
setTilesets(tilesets: PaletteTileset[]): void;
/** Switch which tileset in the list the palette shows/paints from. */
@@ -64,6 +80,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;
+ setActiveAtlas(atlas: AtlasInfo | null): void;
flipH(): void;
flipV(): void;
rotateCW(): void;
@@ -80,6 +97,7 @@ export const useTilemapPaint = create<TilemapPaintState>((set) => ({
selection: null,
clipboard: null,
tool: null,
+ activeAtlas: null,
setTilesets: (tilesets) => set({
tilesets,
activeTileset: 0,
@@ -97,6 +115,7 @@ export const useTilemapPaint = create<TilemapPaintState>((set) => ({
setClipboard: (clipboard) => set({ clipboard }),
setBrushTile: (tileId) => set({ stamp: singleStamp(encodeTile(tileId)) }),
setTerrainSet: (terrainSet) => set({ terrainSet }),
+ setActiveAtlas: (activeAtlas) => set({ activeAtlas }),
flipH: () => set((s) => ({ stamp: flipStampH(s.stamp) })),
flipV: () => set((s) => ({ stamp: flipStampV(s.stamp) })),
rotateCW: () => set((s) => ({ stamp: rotateStampCW(s.stamp) })),
diff --git a/desktop/src/theme/app.css b/desktop/src/theme/app.css
index d1d55b0e5..620a66367 100644
--- a/desktop/src/theme/app.css
+++ b/desktop/src/theme/app.css
@@ -233,6 +233,23 @@
box-shadow: inset 0 0 0 1px rgba(14, 15, 18, 0.5);
will-change: transform, width, height, opacity;
}
+/* WYSIWYG brush ghost: the real stamp tiles, laid out at natural tile pixels; the rAF
+ translates + scales the whole container onto the hovered footprint (transform-origin
+ top-left). Slightly translucent + outlined so it reads as a preview, not painted. */
+.viewport__tileghost {
+ position: absolute;
+ top: 0;
+ left: 0;
+ z-index: 2;
+ opacity: 0;
+ pointer-events: none;
+ transform-origin: 0 0;
+ outline: 1px solid rgba(255, 255, 255, 0.85);
+ will-change: transform, opacity;
+}
+.viewport__tileghost-cell {
+ opacity: 0.72;
+}
/* Gesture-paint preview (rect fill / line cells) container — the ghost cells are
pooled child divs the rAF positions; the container itself is inert. */
.viewport__tilepaint {
@@ -469,6 +486,26 @@ body.thumb-capture .viewport__play-stop {
box-shadow: var(--run-glow);
}
+/* Tile-paint mode badge — mirrors the play flag but in the tile-editing accent, so
+ "you are painting tiles (Q/Esc to leave)" reads at a glance. Edit-mode only, so it
+ never collides with the play flag. */
+.viewport__tileflag {
+ position: absolute;
+ top: 10px;
+ left: 50%;
+ transform: translateX(-50%);
+ z-index: 3;
+ font-size: var(--fs-xs);
+ font-weight: 600;
+ letter-spacing: 0.06em;
+ color: #58b6e6;
+ background: rgba(var(--glass-rgb), 0.8);
+ border: 1px solid rgba(88, 182, 230, 0.5);
+ padding: 4px 12px;
+ border-radius: 999px;
+ pointer-events: none;
+}
+
/* Engine boot / error overlay, centered over the stage. */
.viewport__status {
position: absolute;
diff --git a/desktop/src/theme/tilemap.css b/desktop/src/theme/tilemap.css
index 34b26df3c..00199c9eb 100644
--- a/desktop/src/theme/tilemap.css
+++ b/desktop/src/theme/tilemap.css
@@ -20,9 +20,78 @@
background: var(--srf-2, #1b1e23);
flex: 0 0 auto;
}
+
+/* Layer strip — the scene's tilemap layers (paint targets); the active one is the
+ selection. Each chip: visibility eye · name (click = make active) · lock. */
+.tp-layers {
+ display: flex;
+ align-items: center;
+ gap: 4px;
+ padding: 5px 8px;
+ overflow-x: auto;
+ background: var(--srf-2, #1b1e23);
+ border-bottom: 1px solid var(--line, #2a2d33);
+ flex: 0 0 auto;
+}
+.tp-layer {
+ flex: 0 0 auto;
+ display: inline-flex;
+ align-items: center;
+ background: var(--control, #24272d);
+ border: 1px solid var(--line, #2a2d33);
+ border-radius: 3px;
+ overflow: hidden;
+}
+.tp-layer.is-active { border-color: var(--star, #4c8fd6); background: rgba(76, 143, 214, 0.16); }
+.tp-layer-vis,
+.tp-layer-lock {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ width: 22px;
+ align-self: stretch;
+ background: none;
+ border: none;
+ color: var(--text-faint, #6b717c);
+ cursor: pointer;
+}
+.tp-layer-vis:hover,
+.tp-layer-lock:hover { color: var(--text, #d6d9de); background: var(--control-hover, #333740); }
+.tp-layer-name {
+ background: none;
+ border: none;
+ color: var(--text-dim, #9aa0aa);
+ padding: 4px 7px;
+ cursor: pointer;
+ font: inherit;
+ white-space: nowrap;
+ max-width: 130px;
+ overflow: hidden;
+ text-overflow: ellipsis;
+}
+.tp-layer.is-active .tp-layer-name { color: var(--text, #d6d9de); }
+.tp-layer-name:hover { color: var(--text, #d6d9de); }
.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-brush {
+ display: inline-flex;
+ align-items: center;
+ gap: 6px;
+ color: var(--text-faint, #6b717c);
+ font-variant-numeric: tabular-nums;
+}
+/* Live thumbnail of the active brush (real tiles + orientation) — the ghost geometry
+ laid at natural px inside a fixed box, scaled to fit. */
+.tp-brushthumb {
+ position: relative;
+ display: inline-block;
+ overflow: hidden;
+ border: 1px solid var(--line, #2a2d33);
+ border-radius: 2px;
+ background: var(--srf-0, #101216);
+ image-rendering: pixelated;
+}
+.tp-brushthumb-in { position: absolute; top: 0; left: 0; transform-origin: 0 0; }
.tp-tool {
display: inline-flex;
@@ -43,12 +112,45 @@
color: var(--on-accent, #fff);
}
+/* Palette zoom bar — small tilesets are unclickable at 1:1, so − / + / fit. */
+.tp-palbar {
+ display: flex;
+ align-items: center;
+ gap: 4px;
+ padding: 4px 8px;
+ background: var(--srf-0, #101216);
+ border-bottom: 1px solid var(--line, #2a2d33);
+ flex: 0 0 auto;
+}
+.tp-zbtn {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ width: 22px;
+ height: 20px;
+ background: var(--control, #24272d);
+ border: 1px solid var(--line, #2a2d33);
+ border-radius: 3px;
+ color: var(--text-dim, #9aa0aa);
+ cursor: pointer;
+}
+.tp-zbtn:hover { color: var(--text, #d6d9de); border-color: var(--control-hover, #333740); }
+.tp-zpct {
+ min-width: 42px;
+ text-align: center;
+ color: var(--text-faint, #6b717c);
+ font-variant-numeric: tabular-nums;
+}
+
.tp-palette {
flex: 1 1 auto;
overflow: auto;
padding: 12px;
background: var(--srf-0, #101216);
}
+/* Sizer carries the zoomed layout box (natural × zoom) so the palette scrolls; the atlas
+ inside is drawn at natural size and CSS-scaled to fill it (crisp hit-testing + pixels). */
+.tp-atlas-sizer { position: relative; }
.tp-atlas { position: relative; }
.tp-img { display: block; image-rendering: pixelated; user-select: none; }
diff --git a/desktop/src/theme/viewport.css b/desktop/src/theme/viewport.css
index 34dd53f1c..1168207d9 100644
--- a/desktop/src/theme/viewport.css
+++ b/desktop/src/theme/viewport.css
@@ -172,6 +172,7 @@
width: max-content;
}
.vp-coord .ro strong { color: var(--text); }
+.vp-coord .ro .hud-tile { color: #58b6e6; }
.vp-coord .hint { color: var(--text-mute); font-family: var(--sans); padding-left: 2px; }
/* Play In Viewport (UE5 PIE): the realm iframe overlays the stage while playing. */
diff --git a/desktop/src/tools/index.ts b/desktop/src/tools/index.ts
index ef2644af8..4ae320575 100644
--- a/desktop/src/tools/index.ts
+++ b/desktop/src/tools/index.ts
@@ -7,21 +7,17 @@
* the transform tool (select/move/rotate/scale) is active. The Viewport
* calls this per pointer-down and routes the stroke to the returned tool.
*/
-import { SceneModel } from '@/engine/SceneModel';
-import { useSelection } from '@/store/selectionStore';
import { useEditorStore } from '@/store/editorStore';
import { useTilemapPaint } from '@/store/tilemapPaintStore';
import { TRANSFORM_TOOLS } from './transformTools';
import { TILE_TOOLS } from './tileTools';
+import { isTilePaintMode } from './tileMode';
import type { EditorTool } from './EditorTool';
export function resolveActiveTool(): EditorTool {
- 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) return TILE_TOOLS[paint.tool];
+ if (isTilePaintMode()) return TILE_TOOLS[useTilemapPaint.getState().tool!];
return TRANSFORM_TOOLS[useEditorStore.getState().tool] ?? TRANSFORM_TOOLS.select;
}
export type { EditorTool, PointerInput, ToolContext } from './EditorTool';
+export { isTilemapSelected, isTilePaintMode } from './tileMode';
diff --git a/desktop/src/tools/tileMode.ts b/desktop/src/tools/tileMode.ts
new file mode 100644
index 000000000..f7e0b34ab
--- /dev/null
+++ b/desktop/src/tools/tileMode.ts
@@ -0,0 +1,103 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file tileMode.ts
+ * @brief The single source of truth for "am I in tile-editing context" and the ONE
+ * keyboard handler for tile painting. Centralising the keymap here (instead of
+ * a second `window` keydown listener in the painter panel) is what makes tile
+ * keys work regardless of which panels are mounted AND lets the global keymap
+ * give them priority — so a paint shortcut no longer double-fires the transform
+ * command bound to the same letter (e.g. `R` rotating the stamp AND silently
+ * switching the transform tool to Scale).
+ *
+ * Modality: a tilemap being SELECTED is the tile context. Non-colliding letters
+ * (B/U/L/G/M/I/T, plus E for erase) enter a paint tool from there. The letters that
+ * collide with the transform tools (Q/W/E/R) are consumed for painting ONLY while a
+ * paint tool is active, and Q/W then double as the explicit exit back to
+ * select/move — so there is never a hidden "painting yet the toolbar says Scale" state.
+ */
+import { SceneModel } from '@/engine/SceneModel';
+import { useSelection } from '@/store/selectionStore';
+import { useEditorStore } from '@/store/editorStore';
+import { useTilemapPaint, type PaintTool } from '@/store/tilemapPaintStore';
+import { copySelection, cutSelection, deleteSelection, pasteClipboard } from './tileClipboard';
+import type { ToolMode } from '@/types';
+
+/** True when the primary selection is a TilemapLayer entity — the tile-editing context. */
+export function isTilemapSelected(): boolean {
+ const id = useSelection.getState().selectedId;
+ return id != null
+ && !!SceneModel.entityBySource(id)?.components.some((c) => c.type === 'TilemapLayer');
+}
+
+/** True when a paint tool is active over a selected tilemap — i.e. clicks paint, not select. */
+export function isTilePaintMode(): boolean {
+ return useTilemapPaint.getState().tool != null && isTilemapSelected();
+}
+
+/** The selected tilemap layer's authoring cell size, or null if none is selected. */
+export function selectedTilemapCellSize(): { x: number; y: number } | null {
+ const id = useSelection.getState().selectedId;
+ if (id == null) return null;
+ const layer = SceneModel.entityBySource(id)?.components.find((c) => c.type === 'TilemapLayer');
+ const cell = (layer?.data as { cellSize?: { x: number; y: number } } | undefined)?.cellSize;
+ return cell && cell.x > 0 ? cell : null;
+}
+
+/** Leave paint mode and hand the pointer back to a transform tool (the explicit exit). */
+export function exitTilePaint(transform: ToolMode = 'select'): void {
+ useTilemapPaint.getState().setTool(null);
+ useEditorStore.getState().setTool(transform);
+}
+
+/** Single-key hint shown on each paint tool button — one key per tool, no collisions
+ * among themselves (Q/W/E/R stay the transform tools until you're actually painting). */
+export const TILE_TOOL_KEY: Record<PaintTool, string> = {
+ brush: 'B', erase: 'E', rect: 'U', line: 'L', bucket: 'G', select: 'M', eyedropper: 'I', terrain: 'T',
+};
+
+// Keys that select a paint tool from the tile context whether or not one is active yet.
+// Deliberately excludes the transform letters except E (erasing is worth the override —
+// tilemaps are rarely keyboard-rotated; rotate/scale stay reachable via the toolbar).
+const ENTRY_KEY: Record<string, PaintTool> = {
+ b: 'brush', e: 'erase', u: 'rect', l: 'line', g: 'bucket', m: 'select', i: 'eyedropper', t: 'terrain',
+};
+
+/**
+ * The tile-context keyboard handler. Returns true if it consumed the event, in which
+ * case the caller must {@link KeyboardEvent.preventDefault} and NOT dispatch the global
+ * command bound to the same key. A no-op (returns false) whenever no tilemap is selected.
+ */
+export function handleTilePaintKey(e: KeyboardEvent): boolean {
+ if (!isTilemapSelected()) return false;
+ const paint = useTilemapPaint.getState();
+ const painting = paint.tool != null;
+ const mod = e.metaKey || e.ctrlKey;
+ const k = e.key.toLowerCase();
+
+ // Tile-scoped clipboard — consume so the entity clipboard commands don't also run
+ // (⌘C over a tile selection copies the region, not the tilemap entity).
+ if (painting) {
+ if (paint.tool === 'select') {
+ if (mod && k === 'c') { copySelection(); return true; }
+ if (mod && k === 'x') { cutSelection(); return true; }
+ if (!mod && (e.key === 'Delete' || e.key === 'Backspace')) { deleteSelection(); return true; }
+ }
+ if (mod && k === 'v') { pasteClipboard(); return true; }
+ }
+ // Leave every other modifier chord (undo/save/…) to the global keymap.
+ if (mod || e.altKey) return false;
+
+ // Enter / switch paint tool.
+ const entry = ENTRY_KEY[k];
+ if (entry) { paint.setTool(entry); return true; }
+
+ // The rest only bind while painting, so transform Q/W/E/R work normally otherwise.
+ if (!painting) return false;
+ if (k === 'r') { paint.rotateCW(); return true; }
+ if (k === 'h') { paint.flipH(); return true; }
+ if (k === 'v') { paint.flipV(); return true; }
+ if (k === 'q') { exitTilePaint('select'); return true; }
+ if (k === 'w') { exitTilePaint('move'); return true; }
+ return false;
+}
diff --git a/desktop/src/tools/tileStampGhost.ts b/desktop/src/tools/tileStampGhost.ts
new file mode 100644
index 000000000..9e116f5ae
--- /dev/null
+++ b/desktop/src/tools/tileStampGhost.ts
@@ -0,0 +1,72 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file tileStampGhost.ts
+ * @brief Turns the active brush {@link TileStamp} into a set of translucent atlas-tile
+ * slices for the viewport's WYSIWYG hover ghost — you see the ACTUAL tiles (and
+ * their flip/rotate orientation) that will land, not a blank box. Pure geometry
+ * over the palette's {@link AtlasInfo} (the single source of atlas layout,
+ * published by the painter), so the viewport never re-loads the atlas image.
+ *
+ * Each cell is laid out at NATURAL tile pixels (left/top in tile units × tileW/H); the
+ * viewport scales the whole container to the on-screen footprint each frame, so only one
+ * transform updates per frame while the slices themselves are built once per stamp.
+ */
+import { tileIdOf, tileFlagsOf, type TileStamp } from 'esengine';
+import type { CSSProperties } from 'react';
+import type { AtlasInfo } from '@/store/tilemapPaintStore';
+
+export interface GhostCell {
+ /** Natural-pixel style (position + atlas slice + orientation) for one ghost tile. */
+ style: CSSProperties;
+}
+
+// The 8 D4 orientations of the Tiled flip bits as a CSS 2×2 matrix (a,b,c,d), applied
+// about the tile centre. Identity/H/V/HV are exact; the diagonal set follows Tiled's
+// main-diagonal transpose convention (D swaps x/y, then H/V) — a preview, so a rare
+// mismatch on a rotated tile is cosmetic, not a data error.
+function orientationMatrix(flipH: boolean, flipV: boolean, flipD: boolean): string {
+ const sH = flipH ? -1 : 1;
+ const sV = flipV ? -1 : 1;
+ if (!flipD) return `matrix(${sH}, 0, 0, ${sV}, 0, 0)`;
+ // D transposes ([[0,1],[1,0]]) then H/V flip → (a,b,c,d) = (0, sH, sV, 0).
+ return `matrix(0, ${sH}, ${sV}, 0, 0, 0)`;
+}
+
+/**
+ * Build the ghost tile slices for `stamp` against the active tileset `atlas`, or null
+ * when there's nothing to draw (no atlas, empty stamp, or every cell is out of the
+ * active tileset's id range — e.g. a stamp lifted from another tileset).
+ */
+export function buildStampGhost(stamp: TileStamp, atlas: AtlasInfo | null): GhostCell[] | null {
+ if (!atlas || atlas.cols <= 0) return null;
+ const { url, cols, tileW, tileH, margin, spacing, firstId } = atlas;
+ const cells: GhostCell[] = [];
+ for (let dy = 0; dy < stamp.h; dy++) {
+ for (let dx = 0; dx < stamp.w; dx++) {
+ const raw = stamp.cells[dy * stamp.w + dx];
+ const id = tileIdOf(raw);
+ if (id === 0) continue; // sparse — empty cells paint nothing, so show nothing
+ const local = id - firstId;
+ if (local < 0) continue; // belongs to another tileset — no atlas slice here
+ const col = local % cols;
+ const row = Math.floor(local / cols);
+ const f = tileFlagsOf(raw);
+ cells.push({
+ style: {
+ position: 'absolute',
+ left: dx * tileW,
+ top: dy * tileH,
+ width: tileW,
+ height: tileH,
+ backgroundImage: `url("${url}")`,
+ backgroundPosition: `-${margin + col * (tileW + spacing)}px -${margin + row * (tileH + spacing)}px`,
+ backgroundRepeat: 'no-repeat',
+ transform: orientationMatrix(f.flipH, f.flipV, f.flipD),
+ imageRendering: 'pixelated',
+ },
+ });
+ }
+ }
+ return cells.length > 0 ? cells : null;
+}
diff --git a/desktop/src/tools/tileTools.ts b/desktop/src/tools/tileTools.ts
index e6ec73485..83a955110 100644
--- a/desktop/src/tools/tileTools.ts
+++ b/desktop/src/tools/tileTools.ts
@@ -87,7 +87,7 @@ interface StrokeSpec<C> {
}
function makeStrokeTool<C>(spec: StrokeSpec<C>): EditorTool {
- let active: { ctx: C; sourceId: number; last: string } | null = null;
+ let active: { ctx: C; sourceId: number; last: { x: number; y: number } } | null = null;
return {
id: spec.id,
onPointerDown(p, ctx) {
@@ -98,7 +98,7 @@ function makeStrokeTool<C>(spec: StrokeSpec<C>): EditorTool {
const c = spec.begin(selId);
if (c == null) return false;
spec.onCell(c, tile.x, tile.y);
- active = { ctx: c, sourceId: selId, last: `${tile.x},${tile.y}` };
+ active = { ctx: c, sourceId: selId, last: { x: tile.x, y: tile.y } };
ctx.capture(p.pointerId);
return true;
},
@@ -106,10 +106,13 @@ function makeStrokeTool<C>(spec: StrokeSpec<C>): EditorTool {
if (!active) return;
const tile = cursorTile(p.clientX, p.clientY, active.sourceId);
if (!tile) return;
- const key = `${tile.x},${tile.y}`;
- if (key === active.last) return;
- spec.onCell(active.ctx, tile.x, tile.y);
- active.last = key;
+ if (tile.x === active.last.x && tile.y === active.last.y) return;
+ // Fill every cell from the last sample to this one so a fast drag can't skip cells
+ // (Bresenham). `last` is already painted, so drop the first point of the line.
+ for (const c of lineCells(active.last.x, active.last.y, tile.x, tile.y).slice(1)) {
+ spec.onCell(active.ctx, c.x, c.y);
+ }
+ active.last = { x: tile.x, y: tile.y };
},
onPointerUp(p, ctx) {
if (!active) return;
diff --git a/desktop/tests/tile-mode.test.ts b/desktop/tests/tile-mode.test.ts
new file mode 100644
index 000000000..e02f5f5a6
--- /dev/null
+++ b/desktop/tests/tile-mode.test.ts
@@ -0,0 +1,136 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file The tile-editing keyboard router (handleTilePaintKey) — the single dispatch
+ * point that fixes the old double-fire (a paint shortcut ALSO running the
+ * transform command bound to the same letter). Locks the modality: entry letters
+ * pick a paint tool; the transform-colliding letters (Q/W/R) are claimed only
+ * while painting, and Q/W double as the explicit exit — so the keys never both
+ * paint and switch the transform tool. SceneModel + the tile clipboard are mocked
+ * so this exercises the routing decisions, not the model.
+ */
+import { describe, it, expect, beforeEach, vi } from 'vitest';
+import { tileFlagsOf } from 'esengine';
+
+const model = vi.hoisted(() => ({
+ entity: null as null | { components: { type: string; data: unknown }[] },
+}));
+vi.mock('@/engine/SceneModel', () => ({
+ SceneModelImpl: class {},
+ SceneModel: {
+ subscribe: () => () => {},
+ // Entity #1 is our tilemap; everything else is a plain (non-tile) entity.
+ entityBySource: (id: number) => (id === 1 ? model.entity : null),
+ },
+}));
+
+const clip = vi.hoisted(() => ({
+ copySelection: vi.fn(),
+ cutSelection: vi.fn(),
+ deleteSelection: vi.fn(),
+ pasteClipboard: vi.fn(),
+}));
+vi.mock('@/tools/tileClipboard', () => clip);
+
+import { handleTilePaintKey, isTilemapSelected } from '@/tools/tileMode';
+import { useSelection } from '@/store/selectionStore';
+import { useTilemapPaint } from '@/store/tilemapPaintStore';
+import { useEditorStore } from '@/store/editorStore';
+
+const paint = () => useTilemapPaint.getState();
+const key = (k: string, mods: Partial<KeyboardEvent> = {}): KeyboardEvent =>
+ ({ key: k, metaKey: false, ctrlKey: false, altKey: false, ...mods }) as KeyboardEvent;
+
+describe('tile-editing keyboard router', () => {
+ beforeEach(() => {
+ model.entity = { components: [{ type: 'TilemapLayer', data: { cellSize: { x: 16, y: 16 } } }] };
+ useSelection.getState().select(1);
+ paint().setBrushTile(1);
+ paint().setTool(null);
+ useEditorStore.getState().setTool('move');
+ clip.copySelection.mockClear();
+ clip.cutSelection.mockClear();
+ clip.deleteSelection.mockClear();
+ clip.pasteClipboard.mockClear();
+ });
+
+ it('is inert when no tilemap is selected (transform keys stay global)', () => {
+ model.entity = null;
+ expect(isTilemapSelected()).toBe(false);
+ expect(handleTilePaintKey(key('b'))).toBe(false);
+ expect(paint().tool).toBeNull();
+ });
+
+ it('entry letters pick a paint tool and consume the key', () => {
+ const cases: [string, string][] = [
+ ['b', 'brush'], ['e', 'erase'], ['u', 'rect'], ['l', 'line'],
+ ['g', 'bucket'], ['m', 'select'], ['i', 'eyedropper'], ['t', 'terrain'],
+ ];
+ for (const [k, tool] of cases) {
+ paint().setTool(null);
+ expect(handleTilePaintKey(key(k))).toBe(true);
+ expect(paint().tool).toBe(tool);
+ }
+ });
+
+ it('E claims erase over the transform Rotate command whenever a tilemap is selected', () => {
+ paint().setTool(null); // not painting yet
+ expect(handleTilePaintKey(key('e'))).toBe(true);
+ expect(paint().tool).toBe('erase');
+ });
+
+ it('R rotates the stamp while painting (consumed — never reaches transform Scale)', () => {
+ paint().setTool('brush');
+ paint().setStamp({ w: 2, h: 1, cells: [1, 2] });
+ expect(handleTilePaintKey(key('r'))).toBe(true);
+ expect(paint().stamp).toMatchObject({ w: 1, h: 2 });
+ });
+
+ it('H / V flip the stamp while painting', () => {
+ paint().setTool('brush');
+ paint().setStamp({ w: 2, h: 1, cells: [1, 2] });
+ expect(handleTilePaintKey(key('h'))).toBe(true);
+ expect(tileFlagsOf(paint().stamp.cells[0]).flipH).toBe(true);
+ });
+
+ it('Q / W exit paint mode back to the matching transform tool', () => {
+ paint().setTool('brush');
+ expect(handleTilePaintKey(key('q'))).toBe(true);
+ expect(paint().tool).toBeNull();
+ expect(useEditorStore.getState().tool).toBe('select');
+
+ paint().setTool('brush');
+ expect(handleTilePaintKey(key('w'))).toBe(true);
+ expect(paint().tool).toBeNull();
+ expect(useEditorStore.getState().tool).toBe('move');
+ });
+
+ it('leaves Q / W / R to the global transform commands when a tilemap is selected but not painting', () => {
+ paint().setTool(null);
+ expect(handleTilePaintKey(key('q'))).toBe(false);
+ expect(handleTilePaintKey(key('w'))).toBe(false);
+ expect(handleTilePaintKey(key('r'))).toBe(false);
+ });
+
+ it('routes tile clipboard keys for the select tool (not the entity clipboard)', () => {
+ paint().setTool('select');
+ expect(handleTilePaintKey(key('c', { metaKey: true }))).toBe(true);
+ expect(clip.copySelection).toHaveBeenCalledTimes(1);
+ expect(handleTilePaintKey(key('x', { metaKey: true }))).toBe(true);
+ expect(clip.cutSelection).toHaveBeenCalledTimes(1);
+ expect(handleTilePaintKey(key('Delete'))).toBe(true);
+ expect(clip.deleteSelection).toHaveBeenCalledTimes(1);
+ });
+
+ it('paste routes to the tile clipboard from any paint tool', () => {
+ paint().setTool('brush');
+ expect(handleTilePaintKey(key('v', { metaKey: true }))).toBe(true);
+ expect(clip.pasteClipboard).toHaveBeenCalledTimes(1);
+ });
+
+ it('leaves non-tile modifier chords (undo / save) to the global keymap', () => {
+ paint().setTool('brush');
+ expect(handleTilePaintKey(key('z', { metaKey: true }))).toBe(false);
+ expect(handleTilePaintKey(key('s', { metaKey: true }))).toBe(false);
+ });
+});
diff --git a/desktop/tests/tile-stamp-ghost.test.ts b/desktop/tests/tile-stamp-ghost.test.ts
new file mode 100644
index 000000000..3f5cfb117
--- /dev/null
+++ b/desktop/tests/tile-stamp-ghost.test.ts
@@ -0,0 +1,54 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file buildStampGhost — the WYSIWYG brush ghost geometry. Maps a TileStamp's cells to
+ * atlas slices (background-position) against the active tileset's AtlasInfo, honours
+ * margin/spacing + the global firstId, drops out-of-tileset + empty cells, and emits
+ * the flip/rotate orientation matrix. Pure, so it's fully unit-testable.
+ */
+import { describe, it, expect } from 'vitest';
+import { encodeTile, singleStamp, flipStampH, flipStampV } from 'esengine';
+import { buildStampGhost } from '@/tools/tileStampGhost';
+import type { AtlasInfo } from '@/store/tilemapPaintStore';
+
+const atlas = (over: Partial<AtlasInfo> = {}): AtlasInfo => ({
+ url: 'estella://atlas.png', cols: 4, tileW: 16, tileH: 16, margin: 0, spacing: 0, firstId: 1, ...over,
+});
+
+describe('buildStampGhost', () => {
+ it('returns null with no atlas or an empty stamp', () => {
+ expect(buildStampGhost(singleStamp(encodeTile(1)), null)).toBeNull();
+ expect(buildStampGhost(singleStamp(encodeTile(0)), atlas())).toBeNull();
+ });
+
+ it('slices a single tile by its column/row (firstId-relative)', () => {
+ const cells = buildStampGhost(singleStamp(encodeTile(6)), atlas())!; // local 5 → col 1, row 1
+ expect(cells).toHaveLength(1);
+ expect(cells[0].style).toMatchObject({ left: 0, top: 0, width: 16, height: 16 });
+ expect(cells[0].style.backgroundPosition).toBe('-16px -16px');
+ expect(cells[0].style.transform).toBe('matrix(1, 0, 0, 1, 0, 0)'); // no flip
+ });
+
+ it('accounts for margin + spacing in the slice offset', () => {
+ const cells = buildStampGhost(singleStamp(encodeTile(2)), atlas({ margin: 1, spacing: 2 }))!; // col 1
+ expect(cells[0].style.backgroundPosition).toBe('-19px -1px'); // 1 + 1*(16+2) = 19
+ });
+
+ it('lays multi-tile stamps at their grid offsets', () => {
+ const cells = buildStampGhost({ w: 2, h: 1, cells: [encodeTile(1), encodeTile(2)] }, atlas())!;
+ expect(cells).toHaveLength(2);
+ expect(cells.map((c) => c.style.left)).toEqual([0, 16]);
+ });
+
+ it('drops cells outside the active tileset id range', () => {
+ // firstId 10 → tile id 1 is another tileset's tile, so no slice here.
+ expect(buildStampGhost(singleStamp(encodeTile(1)), atlas({ firstId: 10 }))).toBeNull();
+ });
+
+ it('emits the flip orientation matrix', () => {
+ const h = buildStampGhost(flipStampH(singleStamp(encodeTile(1))), atlas())!;
+ expect(h[0].style.transform).toBe('matrix(-1, 0, 0, 1, 0, 0)');
+ const v = buildStampGhost(flipStampV(singleStamp(encodeTile(1))), atlas())!;
+ expect(v[0].style.transform).toBe('matrix(1, 0, 0, -1, 0, 0)');
+ });
+});