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: add tile palette panel and brush gizmo for tilemap editing

esengine71fadafd4a40
diff --git a/editor/src/commands/TilePaintCommand.ts b/editor/src/commands/TilePaintCommand.ts
new file mode 100644
index 000000000..e4626ab18
--- /dev/null
+++ b/editor/src/commands/TilePaintCommand.ts
@@ -0,0 +1,81 @@
+import type { Entity } from 'esengine';
+import type { SceneData, EntityData } from '../types/SceneTypes';
+import { BaseCommand, CommandRegistry, type ChangeEmitter, type SerializedCommand } from './Command';
+
+export interface TileChange {
+ index: number;
+ oldTile: number;
+ newTile: number;
+}
+
+export class TilePaintCommand extends BaseCommand {
+ readonly type = 'tile-paint';
+ readonly description: string;
+
+ constructor(
+ private scene_: SceneData,
+ private entityMap_: Map<number, EntityData>,
+ private entity_: Entity,
+ private changes_: TileChange[],
+ ) {
+ super();
+ this.description = `Paint ${changes_.length} tile(s)`;
+ }
+
+ execute(): void {
+ this.applyTiles_(true);
+ }
+
+ undo(): void {
+ this.applyTiles_(false);
+ }
+
+ canMerge(_other: import('./Command').Command): boolean {
+ return false;
+ }
+
+ emitChangeEvents(emitter: ChangeEmitter, _isUndo: boolean): void {
+ emitter.notifyPropertyChange({
+ entity: this.entity_ as number,
+ componentType: 'TilemapLayer',
+ propertyName: 'tiles',
+ oldValue: undefined,
+ newValue: undefined,
+ });
+ }
+
+ serialize(): SerializedCommand {
+ return {
+ type: this.type,
+ data: {
+ entity: this.entity_ as number,
+ changes: this.changes_,
+ },
+ };
+ }
+
+ static {
+ CommandRegistry.register('tile-paint', (data, scene, entityMap) =>
+ new TilePaintCommand(
+ scene, entityMap,
+ data.entity as number,
+ data.changes as TileChange[],
+ ),
+ );
+ }
+
+ private applyTiles_(forward: boolean): void {
+ const entityData = this.entityMap_.get(this.entity_ as number);
+ if (!entityData) return;
+
+ const component = entityData.components.find(c => c.type === 'TilemapLayer');
+ if (!component) return;
+
+ const tiles = component.data.tiles as number[];
+ if (!tiles) return;
+
+ for (const change of this.changes_) {
+ tiles[change.index] = forward ? change.newTile : change.oldTile;
+ }
+ }
+}
diff --git a/editor/src/gizmos/GizmoRegistry.ts b/editor/src/gizmos/GizmoRegistry.ts
index 8e31153a0..9c800a4fa 100644
--- a/editor/src/gizmos/GizmoRegistry.ts
+++ b/editor/src/gizmos/GizmoRegistry.ts
@@ -29,6 +29,7 @@ export interface GizmoDescriptor {
onDragEnd?(worldX: number, worldY: number, hitData: unknown, ctx: GizmoContext): void;
onHover?(worldX: number, worldY: number, hitData: unknown, ctx: GizmoContext): void;
getCursor?(hitData: unknown): string;
+ isApplicable?(ctx: GizmoContext): boolean;
}
export function registerGizmo(descriptor: GizmoDescriptor): void {
diff --git a/editor/src/gizmos/TileBrushGizmo.ts b/editor/src/gizmos/TileBrushGizmo.ts
new file mode 100644
index 000000000..1f85f58bd
--- /dev/null
+++ b/editor/src/gizmos/TileBrushGizmo.ts
@@ -0,0 +1,267 @@
+import type { GizmoContext, GizmoDescriptor } from './GizmoRegistry';
+import { getTilesetForSource } from './TilesetLoader';
+import { TilePaintCommand, type TileChange } from '../commands/TilePaintCommand';
+import { icons } from '../utils/icons';
+
+interface TileBrushDragState {
+ entityId: number;
+ mapWidth: number;
+ mapHeight: number;
+ tileWidth: number;
+ tileHeight: number;
+ originX: number;
+ originY: number;
+ tiles: number[];
+ changes: Map<number, TileChange>;
+}
+
+function findTilemapLayerData(gctx: GizmoContext): {
+ entityId: number;
+ data: Record<string, unknown>;
+} | null {
+ const entityData = gctx.store.getSelectedEntityData();
+ if (!entityData) return null;
+ const comp = entityData.components.find(c => c.type === 'TilemapLayer');
+ if (!comp) return null;
+ return { entityId: entityData.id, data: comp.data as Record<string, unknown> };
+}
+
+function findTilemapSource(gctx: GizmoContext): string | null {
+ const entityData = gctx.store.getSelectedEntityData();
+ if (!entityData) return null;
+ const comp = entityData.components.find(c => c.type === 'Tilemap');
+ if (comp) return (comp.data as Record<string, unknown>).source as string ?? null;
+ return null;
+}
+
+function worldToTile(
+ worldX: number, worldY: number,
+ originX: number, originY: number,
+ tileWidth: number, tileHeight: number,
+): { tx: number; ty: number } {
+ return {
+ tx: Math.floor((worldX - originX) / tileWidth),
+ ty: Math.floor((originY - worldY) / tileHeight),
+ };
+}
+
+export function createTileBrushGizmo(): GizmoDescriptor {
+ let hoverTile: { tx: number; ty: number } | null = null;
+ let dragState: TileBrushDragState | null = null;
+
+ function getLayerInfo(gctx: GizmoContext): {
+ entityId: number;
+ width: number;
+ height: number;
+ tileWidth: number;
+ tileHeight: number;
+ tiles: number[];
+ originX: number;
+ originY: number;
+ } | null {
+ const layer = findTilemapLayerData(gctx);
+ if (!layer) return null;
+
+ const d = layer.data;
+ const width = d.width as number ?? 0;
+ const height = d.height as number ?? 0;
+ if (width === 0 || height === 0) return null;
+
+ const worldTransform = gctx.store.getWorldTransform(layer.entityId);
+ return {
+ entityId: layer.entityId,
+ width,
+ height,
+ tileWidth: d.tileWidth as number ?? 32,
+ tileHeight: d.tileHeight as number ?? 32,
+ tiles: d.tiles as number[] ?? [],
+ originX: worldTransform.position.x,
+ originY: worldTransform.position.y,
+ };
+ }
+
+ function getTilesetImage(gctx: GizmoContext): {
+ image: HTMLImageElement;
+ columns: number;
+ tileWidth: number;
+ tileHeight: number;
+ } | null {
+ const source = findTilemapSource(gctx);
+ if (!source) return null;
+ const info = getTilesetForSource(source);
+ if (!info?.tilesetImage) return null;
+ return {
+ image: info.tilesetImage,
+ columns: info.tilesetColumns,
+ tileWidth: info.tileWidth,
+ tileHeight: info.tileHeight,
+ };
+ }
+
+ function paintTile(state: TileBrushDragState, tx: number, ty: number, tileId: number): void {
+ if (tx < 0 || tx >= state.mapWidth || ty < 0 || ty >= state.mapHeight) return;
+ const index = ty * state.mapWidth + tx;
+ if (!state.changes.has(index)) {
+ state.changes.set(index, {
+ index,
+ oldTile: state.tiles[index] ?? 0,
+ newTile: tileId,
+ });
+ } else {
+ state.changes.get(index)!.newTile = tileId;
+ }
+ state.tiles[index] = tileId;
+ }
+
+ return {
+ id: 'tile-brush',
+ name: 'Tile Brush',
+ icon: icons.pencil(14),
+ shortcut: 'b',
+ order: 5,
+
+ isApplicable(ctx: GizmoContext): boolean {
+ const entityData = ctx.store.getSelectedEntityData();
+ if (!entityData) return false;
+ return entityData.components.some(
+ c => c.type === 'TilemapLayer' || c.type === 'Tilemap',
+ );
+ },
+
+ hitTest(worldX, worldY, gctx) {
+ const info = getLayerInfo(gctx);
+ if (!info) return { hit: false };
+
+ const tile = worldToTile(worldX, worldY,
+ info.originX, info.originY, info.tileWidth, info.tileHeight);
+
+ if (tile.tx >= 0 && tile.tx < info.width &&
+ tile.ty >= 0 && tile.ty < info.height) {
+ return { hit: true, data: tile };
+ }
+ return { hit: false };
+ },
+
+ draw(gctx) {
+ if (!hoverTile) return;
+
+ const info = getLayerInfo(gctx);
+ if (!info) return;
+
+ const { ctx, zoom } = gctx;
+ const store = gctx.store;
+ const isErase = store.tileBrushMode === 'erase';
+
+ const screenX = info.originX + hoverTile.tx * info.tileWidth;
+ const screenY = -info.originY + hoverTile.ty * info.tileHeight;
+
+ ctx.save();
+
+ if (isErase) {
+ ctx.fillStyle = 'rgba(255, 60, 60, 0.3)';
+ ctx.fillRect(screenX, screenY, info.tileWidth, info.tileHeight);
+ ctx.strokeStyle = 'rgba(255, 60, 60, 0.8)';
+ ctx.lineWidth = 2 / zoom;
+ ctx.beginPath();
+ ctx.moveTo(screenX, screenY);
+ ctx.lineTo(screenX + info.tileWidth, screenY + info.tileHeight);
+ ctx.moveTo(screenX + info.tileWidth, screenY);
+ ctx.lineTo(screenX, screenY + info.tileHeight);
+ ctx.stroke();
+ } else {
+ ctx.fillStyle = 'rgba(100, 200, 255, 0.3)';
+ ctx.fillRect(screenX, screenY, info.tileWidth, info.tileHeight);
+ ctx.strokeStyle = 'rgba(100, 200, 255, 0.8)';
+ ctx.lineWidth = 2 / zoom;
+ ctx.strokeRect(screenX, screenY, info.tileWidth, info.tileHeight);
+ }
+
+ ctx.restore();
+ },
+
+ onDragStart(worldX, worldY, _hitData, gctx) {
+ gctx.setGizmoActive(true);
+ const info = getLayerInfo(gctx);
+ if (!info) return;
+
+ const tile = worldToTile(worldX, worldY,
+ info.originX, info.originY, info.tileWidth, info.tileHeight);
+
+ const isErase = gctx.store.tileBrushMode === 'erase';
+ const tileId = isErase ? 0 : gctx.store.tileBrushSelectedTileId;
+
+ dragState = {
+ entityId: info.entityId,
+ mapWidth: info.width,
+ mapHeight: info.height,
+ tileWidth: info.tileWidth,
+ tileHeight: info.tileHeight,
+ originX: info.originX,
+ originY: info.originY,
+ tiles: info.tiles,
+ changes: new Map(),
+ };
+
+ paintTile(dragState, tile.tx, tile.ty, tileId);
+ gctx.requestRender();
+ },
+
+ onDrag(worldX, worldY, _hitData, gctx, event) {
+ if (!dragState) return;
+
+ const isShiftErase = event?.shiftKey ?? false;
+ const storeErase = gctx.store.tileBrushMode === 'erase';
+ const isErase = isShiftErase || storeErase;
+ const tileId = isErase ? 0 : gctx.store.tileBrushSelectedTileId;
+
+ const tile = worldToTile(worldX, worldY,
+ dragState.originX, dragState.originY,
+ dragState.tileWidth, dragState.tileHeight);
+
+ paintTile(dragState, tile.tx, tile.ty, tileId);
+
+ hoverTile = tile;
+ gctx.requestRender();
+ },
+
+ onDragEnd(_worldX, _worldY, _hitData, gctx) {
+ gctx.setGizmoActive(false);
+ if (!dragState || dragState.changes.size === 0) {
+ dragState = null;
+ return;
+ }
+
+ const changes = Array.from(dragState.changes.values());
+ const entityId = dragState.entityId;
+ dragState = null;
+
+ const store = gctx.store;
+ const cmd = new TilePaintCommand(
+ store.scene,
+ store.entityMap_,
+ entityId,
+ changes,
+ );
+ store.executeCommand(cmd);
+ gctx.requestRender();
+ },
+
+ onHover(worldX, worldY, hitData, gctx) {
+ let newTile: { tx: number; ty: number } | null = null;
+ if (hitData) {
+ const info = getLayerInfo(gctx);
+ if (info) {
+ newTile = worldToTile(worldX, worldY,
+ info.originX, info.originY, info.tileWidth, info.tileHeight);
+ }
+ }
+ if (newTile?.tx === hoverTile?.tx && newTile?.ty === hoverTile?.ty) return;
+ hoverTile = newTile;
+ gctx.requestRender();
+ },
+
+ getCursor(hitData) {
+ return hitData ? 'crosshair' : 'default';
+ },
+ };
+}
diff --git a/editor/src/gizmos/TilemapOverlay.ts b/editor/src/gizmos/TilemapOverlay.ts
index 0835a0340..23d28a38d 100644
--- a/editor/src/gizmos/TilemapOverlay.ts
+++ b/editor/src/gizmos/TilemapOverlay.ts
@@ -1,42 +1,19 @@
import type { OverlayContext } from './ColliderOverlay';
import type { EntityData } from '../types/SceneTypes';
-import { getGlobalPathResolver } from '../asset';
-import { getPlatformAdapter } from '../platform/PlatformAdapter';
-import { isUUID, getAssetLibrary } from '../asset/AssetLibrary';
+import { getTilesetForSource, addTilesetLoadListener } from './TilesetLoader';
const GRID_COLOR = 'rgba(100, 200, 255, 0.5)';
const FALLBACK_TILE_COLOR = 'rgba(100, 200, 255, 0.15)';
-const HIGHLIGHT_COLOR = 'rgba(255, 200, 50, 0.6)';
const ORIGIN_COLOR = 'rgba(255, 80, 80, 0.8)';
-const TILE_ID_COLOR = 'rgba(255, 255, 255, 0.7)';
-
-const TILED_FLIP_H = 0x80000000;
-const TILED_FLIP_V = 0x40000000;
-const TILED_FLIP_D = 0x20000000;
-const TILED_GID_MASK = 0x1FFFFFFF;
-
-interface ParsedTilemapLayer {
- width: number;
- height: number;
- tiles: number[];
-}
-
-interface CachedTilemap {
- tileWidth: number;
- tileHeight: number;
- orientation: string;
- layers: ParsedTilemapLayer[];
- tilesetImage: HTMLImageElement | null;
- tilesetColumns: number;
-}
export class TilemapOverlay {
- private cache_ = new Map<string, CachedTilemap | null>();
- private loading_ = new Set<string>();
private requestRender_: (() => void) | null = null;
+ private unsubscribe_: (() => void) | null = null;
setRenderCallback(cb: () => void): void {
this.requestRender_ = cb;
+ this.unsubscribe_?.();
+ this.unsubscribe_ = addTilesetLoadListener(() => this.requestRender_?.());
}
drawAll(octx: OverlayContext): void {
@@ -44,18 +21,19 @@ export class TilemapOverlay {
for (const entity of store.scene.entities) {
if (!store.isEntityVisible(entity.id)) continue;
- this.drawEntity_(octx, entity);
+ this.drawTilemapEntity_(octx, entity);
+ this.drawTilemapLayerEntity_(octx, entity);
}
}
- private drawEntity_(octx: OverlayContext, entity: EntityData): void {
+ private drawTilemapEntity_(octx: OverlayContext, entity: EntityData): void {
const tilemapComp = entity.components.find(c => c.type === 'Tilemap');
if (!tilemapComp) return;
const source: string = (tilemapComp.data as any).source ?? '';
if (!source) return;
- const cached = this.loadTilemap_(source);
+ const cached = getTilesetForSource(source);
if (!cached) return;
const { ctx, zoom, store } = octx;
@@ -77,22 +55,54 @@ export class TilemapOverlay {
}
this.drawOriginMarker_(ctx, ox, oy, zoom);
+ ctx.restore();
+ }
+
+ private drawTilemapLayerEntity_(octx: OverlayContext, entity: EntityData): void {
+ const layerComp = entity.components.find(c => c.type === 'TilemapLayer');
+ if (!layerComp) return;
+
+ const data = layerComp.data as Record<string, unknown>;
+ const width = data.width as number ?? 0;
+ const height = data.height as number ?? 0;
+ const tileWidth = data.tileWidth as number ?? 32;
+ const tileHeight = data.tileHeight as number ?? 32;
+ const tiles = data.tiles as number[] ?? [];
+ const tilesetColumns = data.tilesetColumns as number ?? 1;
+
+ if (width === 0 || height === 0) return;
+
+ const { ctx, zoom, store } = octx;
+ const worldTransform = store.getWorldTransform(entity.id);
+ const ox = worldTransform.position.x;
+ const oy = -worldTransform.position.y;
+
+ ctx.save();
+
+ this.drawGrid_(ctx, width, height, tileWidth, tileHeight, ox, oy, zoom);
+ if (tiles.length > 0) {
+ this.drawTiles_(ctx, tiles, width, height, tileWidth, tileHeight,
+ tilesetColumns, null, ox, oy);
+ }
+
+ this.drawOriginMarker_(ctx, ox, oy, zoom);
ctx.restore();
}
- private drawLayer_(
+
+ private drawTiles_(
ctx: CanvasRenderingContext2D,
- cached: CachedTilemap,
- layer: ParsedTilemapLayer,
+ tiles: number[], mapWidth: number, mapHeight: number,
+ tileWidth: number, tileHeight: number,
+ tilesetColumns: number,
+ image: HTMLImageElement | null,
ox: number, oy: number,
): void {
- const { tileWidth, tileHeight, tilesetImage, tilesetColumns } = cached;
-
- if (tilesetImage && tilesetImage.complete && tilesetImage.naturalWidth > 0) {
- for (let ty = 0; ty < layer.height; ty++) {
- for (let tx = 0; tx < layer.width; tx++) {
- const tileId = layer.tiles[ty * layer.width + tx] ?? 0;
+ if (image && image.complete && image.naturalWidth > 0) {
+ for (let ty = 0; ty < mapHeight; ty++) {
+ for (let tx = 0; tx < mapWidth; tx++) {
+ const tileId = tiles[ty * mapWidth + tx] ?? 0;
if (tileId === 0) continue;
const tileIndex = tileId - 1;
@@ -100,7 +110,7 @@ export class TilemapOverlay {
const sy = Math.floor(tileIndex / tilesetColumns) * tileHeight;
ctx.drawImage(
- tilesetImage,
+ image,
sx, sy, tileWidth, tileHeight,
ox + tx * tileWidth, oy + ty * tileHeight, tileWidth, tileHeight,
);
@@ -108,9 +118,9 @@ export class TilemapOverlay {
}
} else {
ctx.fillStyle = FALLBACK_TILE_COLOR;
- for (let ty = 0; ty < layer.height; ty++) {
- for (let tx = 0; tx < layer.width; tx++) {
- const tileId = layer.tiles[ty * layer.width + tx] ?? 0;
+ for (let ty = 0; ty < mapHeight; ty++) {
+ for (let tx = 0; tx < mapWidth; tx++) {
+ const tileId = tiles[ty * mapWidth + tx] ?? 0;
if (tileId === 0) continue;
ctx.fillRect(
ox + tx * tileWidth + 1, oy + ty * tileHeight + 1,
@@ -190,108 +200,4 @@ export class TilemapOverlay {
ctx.arc(ox, oy, size, 0, Math.PI * 2);
ctx.fill();
}
-
- private loadTilemap_(source: string): CachedTilemap | null {
- if (this.cache_.has(source)) {
- return this.cache_.get(source) ?? null;
- }
- if (this.loading_.has(source)) {
- return null;
- }
-
- this.loading_.add(source);
- this.loadTilemapAsync_(source).then(result => {
- this.cache_.set(source, result);
- this.loading_.delete(source);
- if (result) {
- this.requestRender_?.();
- }
- });
- return null;
- }
-
- private resolveSource_(source: string): string {
- if (isUUID(source)) {
- return getAssetLibrary().getPath(source) ?? source;
- }
- return source;
- }
-
- private async loadTilemapAsync_(source: string): Promise<CachedTilemap | null> {
- try {
- const resolver = getGlobalPathResolver();
- if (!resolver) return null;
-
- const platform = getPlatformAdapter();
- const resolvedPath = this.resolveSource_(source);
- const absPath = resolver.toAbsolutePath(resolvedPath);
- const jsonText = await platform.readTextFile(absPath);
- const json = JSON.parse(jsonText) as Record<string, unknown>;
-
- const mapWidth = json.width as number;
- const mapHeight = json.height as number;
- const tileWidth = (json.tilewidth as number) ?? 32;
- const tileHeight = (json.tileheight as number) ?? 32;
- if (!mapWidth || !mapHeight) return null;
-
- const rawTilesets = json.tilesets as Array<Record<string, unknown>> | undefined;
- const firstGid = rawTilesets?.[0]?.firstgid as number ?? 1;
- const tilesetImage = rawTilesets?.[0]?.image as string ?? '';
- const tilesetColumns = (rawTilesets?.[0]?.columns as number) ?? 1;
-
- const rawLayers = json.layers as Array<Record<string, unknown>> | undefined;
- const layers: ParsedTilemapLayer[] = [];
-
- if (rawLayers) {
- for (const layer of rawLayers) {
- if (layer.type !== 'tilelayer') continue;
- const lw = (layer.width as number) ?? mapWidth;
- const lh = (layer.height as number) ?? mapHeight;
- if (layer.visible === false) continue;
- const rawData = layer.data as number[] | undefined;
- const tiles: number[] = [];
- if (rawData) {
- for (const gid of rawData) {
- if (gid === 0) {
- tiles.push(0);
- } else {
- const localId = (gid & TILED_GID_MASK) - firstGid;
- tiles.push(localId + 1);
- }
- }
- }
- layers.push({ width: lw, height: lh, tiles });
- }
- }
-
- let loadedImage: HTMLImageElement | null = null;
- if (tilesetImage) {
- const baseDir = resolvedPath.substring(0, resolvedPath.lastIndexOf('/') + 1);
- const imagePath = baseDir + tilesetImage;
- const absImagePath = resolver.toAbsolutePath(imagePath);
- const imageUrl = platform.convertFilePathToUrl(absImagePath);
-
- const img = new Image();
- img.src = imageUrl;
- await new Promise<void>((resolve, reject) => {
- img.onload = () => resolve();
- img.onerror = () => reject(new Error('Failed to load tileset image'));
- });
- loadedImage = img;
- }
-
- const orientation = (json.orientation as string) ?? 'orthogonal';
-
- return {
- tileWidth,
- tileHeight,
- orientation,
- layers,
- tilesetImage: loadedImage,
- tilesetColumns,
- };
- } catch {
- return null;
- }
- }
}
diff --git a/editor/src/gizmos/TilesetLoader.ts b/editor/src/gizmos/TilesetLoader.ts
new file mode 100644
index 000000000..3d868edc1
--- /dev/null
+++ b/editor/src/gizmos/TilesetLoader.ts
@@ -0,0 +1,185 @@
+import { getGlobalPathResolver } from '../asset';
+import { getPlatformAdapter } from '../platform/PlatformAdapter';
+import { isUUID, getAssetLibrary } from '../asset/AssetLibrary';
+
+const TILED_GID_MASK = 0x1FFFFFFF;
+
+export interface ParsedTilemapLayer {
+ width: number;
+ height: number;
+ tiles: number[];
+}
+
+export interface TilesetInfo {
+ tileWidth: number;
+ tileHeight: number;
+ orientation: string;
+ layers: ParsedTilemapLayer[];
+ tilesetImage: HTMLImageElement | null;
+ tilesetColumns: number;
+}
+
+export interface TilesetImageInfo {
+ image: HTMLImageElement;
+ columns: number;
+ tileWidth: number;
+ tileHeight: number;
+}
+
+type LoadState = { status: 'loading' } | { status: 'loaded'; data: TilesetInfo | null };
+
+const cache_ = new Map<string, LoadState>();
+const imageCache_ = new Map<string, HTMLImageElement | null>();
+const listeners_: Set<() => void> = new Set();
+
+export function addTilesetLoadListener(cb: () => void): () => void {
+ listeners_.add(cb);
+ return () => listeners_.delete(cb);
+}
+
+function notifyListeners(): void {
+ for (const cb of listeners_) cb();
+}
+
+function resolveSource(source: string): string {
+ if (isUUID(source)) {
+ return getAssetLibrary().getPath(source) ?? source;
+ }
+ return source;
+}
+
+export function getTilesetForSource(source: string): TilesetInfo | null {
+ const entry = cache_.get(source);
+ if (!entry) {
+ loadTiledSource(source);
+ return null;
+ }
+ if (entry.status === 'loading') return null;
+ return entry.data;
+}
+
+function loadTiledSource(source: string): void {
+ if (cache_.has(source)) return;
+ cache_.set(source, { status: 'loading' });
+
+ loadTiledSourceAsync(source).then(result => {
+ cache_.set(source, { status: 'loaded', data: result });
+ notifyListeners();
+ });
+}
+
+async function loadTiledSourceAsync(source: string): Promise<TilesetInfo | null> {
+ try {
+ const resolver = getGlobalPathResolver();
+ if (!resolver) return null;
+
+ const platform = getPlatformAdapter();
+ const resolvedPath = resolveSource(source);
+ const absPath = resolver.toAbsolutePath(resolvedPath);
+ const jsonText = await platform.readTextFile(absPath);
+ const json = JSON.parse(jsonText) as Record<string, unknown>;
+
+ const mapWidth = json.width as number;
+ const mapHeight = json.height as number;
+ const tileWidth = (json.tilewidth as number) ?? 32;
+ const tileHeight = (json.tileheight as number) ?? 32;
+ if (!mapWidth || !mapHeight) return null;
+
+ const rawTilesets = json.tilesets as Array<Record<string, unknown>> | undefined;
+ const firstGid = rawTilesets?.[0]?.firstgid as number ?? 1;
+ const tilesetImagePath = rawTilesets?.[0]?.image as string ?? '';
+ const tilesetColumns = (rawTilesets?.[0]?.columns as number) ?? 1;
+
+ const rawLayers = json.layers as Array<Record<string, unknown>> | undefined;
+ const layers: ParsedTilemapLayer[] = [];
+
+ if (rawLayers) {
+ for (const layer of rawLayers) {
+ if (layer.type !== 'tilelayer') continue;
+ const lw = (layer.width as number) ?? mapWidth;
+ const lh = (layer.height as number) ?? mapHeight;
+ if (layer.visible === false) continue;
+ const rawData = layer.data as number[] | undefined;
+ const tiles: number[] = [];
+ if (rawData) {
+ for (const gid of rawData) {
+ if (gid === 0) {
+ tiles.push(0);
+ } else {
+ const localId = (gid & TILED_GID_MASK) - firstGid;
+ tiles.push(localId + 1);
+ }
+ }
+ }
+ layers.push({ width: lw, height: lh, tiles });
+ }
+ }
+
+ let loadedImage: HTMLImageElement | null = null;
+ if (tilesetImagePath) {
+ const baseDir = resolvedPath.substring(0, resolvedPath.lastIndexOf('/') + 1);
+ loadedImage = await loadImageFromPath(baseDir + tilesetImagePath);
+ }
+
+ const orientation = (json.orientation as string) ?? 'orthogonal';
+
+ return {
+ tileWidth,
+ tileHeight,
+ orientation,
+ layers,
+ tilesetImage: loadedImage,
+ tilesetColumns,
+ };
+ } catch {
+ return null;
+ }
+}
+
+export async function loadImageFromPath(relativePath: string): Promise<HTMLImageElement | null> {
+ const cached = imageCache_.get(relativePath);
+ if (cached !== undefined) return cached;
+
+ try {
+ const resolver = getGlobalPathResolver();
+ if (!resolver) return null;
+
+ const platform = getPlatformAdapter();
+ const absPath = resolver.toAbsolutePath(relativePath);
+ const imageUrl = platform.convertFilePathToUrl(absPath);
+
+ const img = new Image();
+ img.src = imageUrl;
+ await new Promise<void>((resolve, reject) => {
+ img.onload = () => resolve();
+ img.onerror = () => reject(new Error('Failed to load tileset image'));
+ });
+ imageCache_.set(relativePath, img);
+ return img;
+ } catch {
+ imageCache_.set(relativePath, null);
+ return null;
+ }
+}
+
+export function loadImageFromUrl(url: string): HTMLImageElement | null {
+ const cached = imageCache_.get(url);
+ if (cached !== undefined) return cached;
+
+ imageCache_.set(url, null);
+ const img = new Image();
+ img.src = url;
+ img.onload = () => {
+ imageCache_.set(url, img);
+ notifyListeners();
+ };
+ img.onerror = () => {
+ imageCache_.set(url, null);
+ };
+ return null;
+}
+
+export function clearTilesetCache(): void {
+ cache_.clear();
+ imageCache_.clear();
+}
diff --git a/editor/src/gizmos/builtinGizmos.ts b/editor/src/gizmos/builtinGizmos.ts
index bd5c19049..74344008c 100644
--- a/editor/src/gizmos/builtinGizmos.ts
+++ b/editor/src/gizmos/builtinGizmos.ts
@@ -2,6 +2,7 @@ import type { GizmoContext, GizmoDescriptor } from './GizmoRegistry';
import type { PluginRegistrar } from '../container';
import { GIZMO } from '../container/tokens';
import { icons } from '../utils/icons';
+import { createTileBrushGizmo } from './TileBrushGizmo';
import { quatToEuler, eulerToQuat } from '../math/Transform';
import { getSettingsValue } from '../settings/SettingsRegistry';
import { getSizeProvider } from '../utils/sceneQueries';
@@ -890,4 +891,5 @@ export function registerBuiltinGizmos(registrar: PluginRegistrar): void {
registerGizmo(createRotateGizmo());
registerGizmo(createScaleGizmo());
registerGizmo(createRectGizmo());
+ registerGizmo(createTileBrushGizmo());
}
diff --git a/editor/src/panels/builtinPanels.ts b/editor/src/panels/builtinPanels.ts
index 9a72a0076..8630e5d89 100644
--- a/editor/src/panels/builtinPanels.ts
+++ b/editor/src/panels/builtinPanels.ts
@@ -12,6 +12,7 @@ import { TimelinePanel } from './timeline/TimelinePanel';
import { FrameDebuggerPanel } from './frameDebugger/FrameDebuggerPanel';
import { ExtensionsPanel } from './ExtensionsPanel';
import { StateMachineGraphPanel } from './state-machine-graph/StateMachineGraphPanel';
+import { TilePalettePanel } from './tile-palette/TilePalettePanel';
import { icons } from '../utils/icons';
import { getEditorStore } from '../store';
import { getSceneService } from '../services';
@@ -128,6 +129,16 @@ export function registerBuiltinPanels(registrar: PluginRegistrar, options: Built
factory: (c) => ({ instance: new StateMachineGraphPanel(c, getEditorStore()) }),
});
+ registerPanel({
+ id: 'tile-palette',
+ title: 'Tile Palette',
+ icon: icons.grid(PANEL_ICON_SIZE),
+ position: 'bottom',
+ defaultVisible: false,
+ order: 6,
+ factory: (c) => ({ instance: new TilePalettePanel(c, getEditorStore()) }),
+ });
+
registerPanel({
id: 'extensions',
title: 'Extensions',
diff --git a/editor/src/panels/scene-view/GizmoToolbar.ts b/editor/src/panels/scene-view/GizmoToolbar.ts
index 8eb2f3498..1b3a103b0 100644
--- a/editor/src/panels/scene-view/GizmoToolbar.ts
+++ b/editor/src/panels/scene-view/GizmoToolbar.ts
@@ -1,4 +1,4 @@
-import { GizmoManager, getAllGizmos } from '../../gizmos';
+import { GizmoManager, getAllGizmos, type GizmoContext } from '../../gizmos';
import { getSettingsValue, setSettingsValue, onSettingsChange } from '../../settings/SettingsRegistry';
import { icons } from '../../utils/icons';
@@ -125,6 +125,16 @@ export class GizmoToolbar {
}
}
+ updateApplicability(ctx: GizmoContext): void {
+ const gizmos = getAllGizmos();
+ for (const g of gizmos) {
+ const btn = this.container_.querySelector(`.es-gizmo-btn[data-mode="${g.id}"]`) as HTMLElement | null;
+ if (!btn) continue;
+ const applicable = g.isApplicable ? g.isApplicable(ctx) : true;
+ btn.classList.toggle('es-disabled', !applicable);
+ }
+ }
+
updateSnapIndicator(active: boolean): void {
const indicator = this.container_.querySelector('.es-snap-indicator') as HTMLElement | null;
if (indicator) {
diff --git a/editor/src/panels/tile-palette/TilePalettePanel.ts b/editor/src/panels/tile-palette/TilePalettePanel.ts
new file mode 100644
index 000000000..60cbb0e71
--- /dev/null
+++ b/editor/src/panels/tile-palette/TilePalettePanel.ts
@@ -0,0 +1,319 @@
+import type { PanelInstance } from '../PanelRegistry';
+import type { EditorStore } from '../../store/EditorStore';
+import { DisposableStore } from '../../utils/Disposable';
+import { getTilesetForSource, addTilesetLoadListener, type TilesetInfo } from '../../gizmos/TilesetLoader';
+import { icons } from '../../utils/icons';
+
+const TILE_RENDER_SIZE = 32;
+const SELECTED_COLOR = 'rgba(100, 200, 255, 0.8)';
+const HOVER_COLOR = 'rgba(255, 255, 255, 0.3)';
+const GRID_COLOR = 'rgba(80, 80, 80, 0.5)';
+const BG_COLOR = '#1e1e1e';
+
+export class TilePalettePanel implements PanelInstance {
+ private container_: HTMLElement;
+ private store_: EditorStore;
+ private disposables_ = new DisposableStore();
+ private canvas_: HTMLCanvasElement | null = null;
+ private ctx_: CanvasRenderingContext2D | null = null;
+ private statusEl_: HTMLElement | null = null;
+ private hoveredTile_ = -1;
+ private cachedInfo_: TilesetInfo | null = null;
+ private cachedSource_: string | null = null;
+ private isReadOnly_ = false;
+ private lastSelectedEntityId_ = -1;
+
+ constructor(container: HTMLElement, store: EditorStore) {
+ this.container_ = container;
+ this.store_ = store;
+
+ this.container_.innerHTML = `
+ <div class="es-tile-palette" style="display:flex;flex-direction:column;height:100%;overflow:hidden;">
+ <div class="es-tile-palette-toolbar" style="display:flex;gap:4px;padding:4px;border-bottom:1px solid var(--border-color, #333);align-items:center;">
+ <button class="es-btn es-btn-icon es-tile-tool-paint es-active" data-tooltip="Paint (B)" style="min-width:24px;height:24px;">${icons.pencil(12)}</button>
+ <button class="es-btn es-btn-icon es-tile-tool-erase" data-tooltip="Erase (Shift)" style="min-width:24px;height:24px;">${icons.trash(12)}</button>
+ <span class="es-tile-palette-status" style="margin-left:auto;font-size:11px;color:#888;"></span>
+ </div>
+ <div class="es-tile-palette-canvas-wrap" style="flex:1;overflow-y:auto;position:relative;">
+ <canvas class="es-tile-palette-canvas" style="display:block;"></canvas>
+ </div>
+ </div>`;
+
+ this.canvas_ = this.container_.querySelector('.es-tile-palette-canvas');
+ this.ctx_ = this.canvas_?.getContext('2d') ?? null;
+ this.statusEl_ = this.container_.querySelector('.es-tile-palette-status');
+
+ this.setupToolbarEvents_();
+ this.setupCanvasEvents_();
+
+ this.disposables_.add(store.subscribe(() => this.onStoreChange_()));
+ this.disposables_.add(addTilesetLoadListener(() => this.render_()));
+
+ this.onStoreChange_();
+ }
+
+ dispose(): void {
+ this.disposables_.dispose();
+ }
+
+ onShow(): void {
+ this.render_();
+ }
+
+ private setupToolbarEvents_(): void {
+ const paintBtn = this.container_.querySelector('.es-tile-tool-paint');
+ const eraseBtn = this.container_.querySelector('.es-tile-tool-erase');
+
+ const onPaint = () => {
+ this.store_.tileBrushMode = 'paint';
+ this.updateToolbarActive_();
+ };
+ const onErase = () => {
+ this.store_.tileBrushMode = 'erase';
+ this.updateToolbarActive_();
+ };
+
+ paintBtn?.addEventListener('click', onPaint);
+ eraseBtn?.addEventListener('click', onErase);
+ this.disposables_.add(() => {
+ paintBtn?.removeEventListener('click', onPaint);
+ eraseBtn?.removeEventListener('click', onErase);
+ });
+ }
+
+ private updateToolbarActive_(): void {
+ const mode = this.store_.tileBrushMode;
+ this.container_.querySelector('.es-tile-tool-paint')
+ ?.classList.toggle('es-active', mode === 'paint');
+ this.container_.querySelector('.es-tile-tool-erase')
+ ?.classList.toggle('es-active', mode === 'erase');
+ }
+
+ private setupCanvasEvents_(): void {
+ if (!this.canvas_) return;
+
+ const onClick = (e: MouseEvent) => {
+ if (this.isReadOnly_) return;
+ const tileId = this.getTileAtMouse_(e);
+ if (tileId > 0) {
+ this.store_.tileBrushSelectedTileId = tileId;
+ this.render_();
+ }
+ };
+ const onMove = (e: MouseEvent) => {
+ const tileId = this.getTileAtMouse_(e);
+ if (tileId !== this.hoveredTile_) {
+ this.hoveredTile_ = tileId;
+ this.render_();
+ }
+ };
+ const onLeave = () => {
+ if (this.hoveredTile_ !== -1) {
+ this.hoveredTile_ = -1;
+ this.render_();
+ }
+ };
+
+ this.canvas_.addEventListener('click', onClick);
+ this.canvas_.addEventListener('mousemove', onMove);
+ this.canvas_.addEventListener('mouseleave', onLeave);
+ this.disposables_.add(() => {
+ this.canvas_?.removeEventListener('click', onClick);
+ this.canvas_?.removeEventListener('mousemove', onMove);
+ this.canvas_?.removeEventListener('mouseleave', onLeave);
+ });
+ }
+
+ private getTileAtMouse_(e: MouseEvent): number {
+ if (!this.canvas_ || !this.cachedInfo_) return -1;
+
+ const rect = this.canvas_.getBoundingClientRect();
+ const x = e.clientX - rect.left;
+ const y = e.clientY - rect.top;
+
+ const cols = this.cachedInfo_.tilesetColumns;
+ const col = Math.floor(x / TILE_RENDER_SIZE);
+ const row = Math.floor(y / TILE_RENDER_SIZE);
+
+ if (col < 0 || col >= cols) return -1;
+
+ const totalTiles = this.getTotalTiles_();
+ const totalRows = Math.ceil(totalTiles / cols);
+ if (row < 0 || row >= totalRows) return -1;
+
+ const index = row * cols + col;
+ if (index >= totalTiles) return -1;
+
+ return index + 1;
+ }
+
+ private getTotalTiles_(): number {
+ if (!this.cachedInfo_?.tilesetImage) return 0;
+ const img = this.cachedInfo_.tilesetImage;
+ const cols = this.cachedInfo_.tilesetColumns;
+ const rows = Math.floor(img.naturalHeight / this.cachedInfo_.tileHeight);
+ return cols * rows;
+ }
+
+ private onStoreChange_(): void {
+ const entityData = this.store_.getSelectedEntityData();
+ const entityId = entityData?.id ?? -1;
+
+ if (entityId === this.lastSelectedEntityId_ && this.cachedSource_) return;
+ this.lastSelectedEntityId_ = entityId;
+
+ this.isReadOnly_ = false;
+ this.cachedSource_ = null;
+ this.cachedInfo_ = null;
+
+ if (entityData) {
+ const tilemapComp = entityData.components.find(c => c.type === 'Tilemap');
+ if (tilemapComp) {
+ const source = (tilemapComp.data as Record<string, unknown>).source as string ?? '';
+ if (source) {
+ this.cachedSource_ = source;
+ this.cachedInfo_ = getTilesetForSource(source);
+ this.isReadOnly_ = true;
+ }
+ }
+
+ const layerComp = entityData.components.find(c => c.type === 'TilemapLayer');
+ if (layerComp && !this.cachedSource_) {
+ const parentEntity = this.findParentWithTilemap_(entityData.id);
+ if (parentEntity) {
+ const tmComp = parentEntity.components.find(c => c.type === 'Tilemap');
+ if (tmComp) {
+ const source = (tmComp.data as Record<string, unknown>).source as string ?? '';
+ if (source) {
+ this.cachedSource_ = source;
+ this.cachedInfo_ = getTilesetForSource(source);
+ this.isReadOnly_ = false;
+ }
+ }
+ }
+ }
+ }
+
+ this.render_();
+ }
+
+ private findParentWithTilemap_(entityId: number): import('../../types/SceneTypes').EntityData | null {
+ for (const entity of this.store_.scene.entities) {
+ if (entity.children?.includes(entityId)) {
+ if (entity.components.some(c => c.type === 'Tilemap')) {
+ return entity;
+ }
+ }
+ }
+ return null;
+ }
+
+ private render_(): void {
+ const ctx = this.ctx_;
+ if (!this.canvas_ || !ctx) return;
+
+ if (this.statusEl_) {
+ if (this.isReadOnly_) {
+ this.statusEl_.textContent = 'Read-only (external source)';
+ } else if (this.cachedInfo_) {
+ this.statusEl_.textContent = `Tile: ${this.store_.tileBrushSelectedTileId}`;
+ } else {
+ this.statusEl_.textContent = 'No tilemap selected';
+ }
+ }
+
+ if (!this.cachedInfo_?.tilesetImage) {
+ this.canvas_.width = this.canvas_.parentElement?.clientWidth ?? 200;
+ this.canvas_.height = 100;
+ ctx.fillStyle = BG_COLOR;
+ ctx.fillRect(0, 0, this.canvas_.width, this.canvas_.height);
+ ctx.fillStyle = '#666';
+ ctx.font = '12px sans-serif';
+ ctx.textAlign = 'center';
+ const msg = this.cachedSource_ ? 'Loading tileset...' : 'Select a Tilemap entity';
+ ctx.fillText(msg, this.canvas_.width / 2, 50);
+ return;
+ }
+
+ const info = this.cachedInfo_;
+ const img = info.tilesetImage!;
+ const cols = info.tilesetColumns;
+ const totalTiles = this.getTotalTiles_();
+ const totalRows = Math.ceil(totalTiles / cols);
+
+ const canvasWidth = cols * TILE_RENDER_SIZE;
+ const canvasHeight = totalRows * TILE_RENDER_SIZE;
+
+ this.canvas_.width = canvasWidth;
+ this.canvas_.height = canvasHeight;
+ this.canvas_.style.width = `${canvasWidth}px`;
+ this.canvas_.style.height = `${canvasHeight}px`;
+
+ ctx.fillStyle = BG_COLOR;
+ ctx.fillRect(0, 0, canvasWidth, canvasHeight);
+
+ ctx.imageSmoothingEnabled = false;
+
+ for (let row = 0; row < totalRows; row++) {
+ for (let col = 0; col < cols; col++) {
+ const index = row * cols + col;
+ if (index >= totalTiles) break;
+
+ const sx = col * info.tileWidth;
+ const sy = row * info.tileHeight;
+ const dx = col * TILE_RENDER_SIZE;
+ const dy = row * TILE_RENDER_SIZE;
+
+ ctx.drawImage(
+ img,
+ sx, sy, info.tileWidth, info.tileHeight,
+ dx, dy, TILE_RENDER_SIZE, TILE_RENDER_SIZE,
+ );
+ }
+ }
+
+ ctx.strokeStyle = GRID_COLOR;
+ ctx.lineWidth = 1;
+ for (let x = 0; x <= cols; x++) {
+ ctx.beginPath();
+ ctx.moveTo(x * TILE_RENDER_SIZE + 0.5, 0);
+ ctx.lineTo(x * TILE_RENDER_SIZE + 0.5, canvasHeight);
+ ctx.stroke();
+ }
+ for (let y = 0; y <= totalRows; y++) {
+ ctx.beginPath();
+ ctx.moveTo(0, y * TILE_RENDER_SIZE + 0.5);
+ ctx.lineTo(canvasWidth, y * TILE_RENDER_SIZE + 0.5);
+ ctx.stroke();
+ }
+
+ const selectedId = this.store_.tileBrushSelectedTileId;
+ if (selectedId > 0 && selectedId <= totalTiles) {
+ const si = selectedId - 1;
+ const sc = si % cols;
+ const sr = Math.floor(si / cols);
+ ctx.strokeStyle = SELECTED_COLOR;
+ ctx.lineWidth = 2;
+ ctx.strokeRect(
+ sc * TILE_RENDER_SIZE + 1,
+ sr * TILE_RENDER_SIZE + 1,
+ TILE_RENDER_SIZE - 2,
+ TILE_RENDER_SIZE - 2,
+ );
+ }
+
+ if (this.hoveredTile_ > 0 && this.hoveredTile_ <= totalTiles &&
+ this.hoveredTile_ !== selectedId) {
+ const hi = this.hoveredTile_ - 1;
+ const hc = hi % cols;
+ const hr = Math.floor(hi / cols);
+ ctx.fillStyle = HOVER_COLOR;
+ ctx.fillRect(
+ hc * TILE_RENDER_SIZE,
+ hr * TILE_RENDER_SIZE,
+ TILE_RENDER_SIZE,
+ TILE_RENDER_SIZE,
+ );
+ }
+ }
+}
diff --git a/editor/src/scene/EditorSceneManager.ts b/editor/src/scene/EditorSceneManager.ts
index 617c31ad9..56430ddb0 100644
--- a/editor/src/scene/EditorSceneManager.ts
+++ b/editor/src/scene/EditorSceneManager.ts
@@ -833,6 +833,8 @@ export class EditorSceneManager {
width: l.width,
height: l.height,
tiles: l.tiles,
+ chunks: l.chunks ?? [],
+ infinite: l.infinite ?? false,
})),
tilesets,
});
diff --git a/editor/src/store/EditorStore.ts b/editor/src/store/EditorStore.ts
index 0b441882f..7ec745848 100644
--- a/editor/src/store/EditorStore.ts
+++ b/editor/src/store/EditorStore.ts
@@ -107,6 +107,9 @@ export class EditorStore {
private autoSaveTimer_: ReturnType<typeof setInterval> | null = null;
+ private tileBrushSelectedTileId_ = 1;
+ private tileBrushMode_: 'paint' | 'erase' = 'paint';
+
private readonly selection_: SelectionService;
private readonly sceneOps_: SceneOperations;
private readonly prefabEdit_: PrefabEditService;
@@ -189,6 +192,22 @@ export class EditorStore {
return this.prefabEdit_.isEditingPrefab;
}
+ get tileBrushSelectedTileId(): number {
+ return this.tileBrushSelectedTileId_;
+ }
+
+ set tileBrushSelectedTileId(id: number) {
+ this.tileBrushSelectedTileId_ = id;
+ }
+
+ get tileBrushMode(): 'paint' | 'erase' {
+ return this.tileBrushMode_;
+ }
+
+ set tileBrushMode(mode: 'paint' | 'erase') {
+ this.tileBrushMode_ = mode;
+ }
+
get canUndo(): boolean {
return this.history_.canUndo();
}