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: support native tilemap creation without external Tiled editor

esenginee840bba50006
diff --git a/editor/src/gizmos/TileBrushGizmo.ts b/editor/src/gizmos/TileBrushGizmo.ts
index 1f85f58bd..67e7239f8 100644
--- a/editor/src/gizmos/TileBrushGizmo.ts
+++ b/editor/src/gizmos/TileBrushGizmo.ts
@@ -1,5 +1,5 @@
import type { GizmoContext, GizmoDescriptor } from './GizmoRegistry';
-import { getTilesetForSource } from './TilesetLoader';
+import { getTilesetForSource, getTilesetForImage, findParentTilemapSource } from './TilesetLoader';
import { TilePaintCommand, type TileChange } from '../commands/TilePaintCommand';
import { icons } from '../utils/icons';
@@ -29,9 +29,14 @@ function findTilemapLayerData(gctx: GizmoContext): {
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;
+
+ const tilemapComp = entityData.components.find(c => c.type === 'Tilemap');
+ if (tilemapComp) {
+ const source = (tilemapComp.data as Record<string, unknown>).source as string ?? '';
+ if (source) return source;
+ }
+
+ return findParentTilemapSource(gctx.store.scene.entities, entityData.id);
}
function worldToTile(
@@ -87,19 +92,49 @@ export function createTileBrushGizmo(): GizmoDescriptor {
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,
- };
+ if (source) {
+ const info = getTilesetForSource(source);
+ if (info?.tilesetImage) {
+ return {
+ image: info.tilesetImage,
+ columns: info.tilesetColumns,
+ tileWidth: info.tileWidth,
+ tileHeight: info.tileHeight,
+ };
+ }
+ }
+
+ const layer = findTilemapLayerData(gctx);
+ if (layer) {
+ const d = layer.data;
+ const textureUuid = d.texture as string ?? '';
+ if (textureUuid && typeof textureUuid === 'string') {
+ const tw = d.tileWidth as number ?? 32;
+ const th = d.tileHeight as number ?? 32;
+ const cols = d.tilesetColumns as number ?? 1;
+ const info = getTilesetForImage(textureUuid, tw, th, cols);
+ if (info?.tilesetImage) {
+ return {
+ image: info.tilesetImage,
+ columns: info.tilesetColumns,
+ tileWidth: info.tileWidth,
+ tileHeight: info.tileHeight,
+ };
+ }
+ }
+ }
+
+ return null;
}
function paintTile(state: TileBrushDragState, tx: number, ty: number, tileId: number): void {
if (tx < 0 || tx >= state.mapWidth || ty < 0 || ty >= state.mapHeight) return;
+ const expectedLen = state.mapWidth * state.mapHeight;
+ if (state.tiles.length < expectedLen) {
+ const oldLen = state.tiles.length;
+ state.tiles.length = expectedLen;
+ state.tiles.fill(0, oldLen, expectedLen);
+ }
const index = ty * state.mapWidth + tx;
if (!state.changes.has(index)) {
state.changes.set(index, {
diff --git a/editor/src/gizmos/TilesetLoader.ts b/editor/src/gizmos/TilesetLoader.ts
index 3d868edc1..90f2f7067 100644
--- a/editor/src/gizmos/TilesetLoader.ts
+++ b/editor/src/gizmos/TilesetLoader.ts
@@ -179,6 +179,53 @@ export function loadImageFromUrl(url: string): HTMLImageElement | null {
return null;
}
+export function getTilesetForImage(
+ imageUuid: string,
+ tileWidth: number,
+ tileHeight: number,
+ tilesetColumns: number,
+): TilesetInfo | null {
+ const cacheKey = `img:${imageUuid}:${tileWidth}:${tileHeight}:${tilesetColumns}`;
+ const entry = cache_.get(cacheKey);
+ if (entry) {
+ return entry.status === 'loaded' ? entry.data : null;
+ }
+
+ const path = resolveSource(imageUuid);
+ if (path === imageUuid && isUUID(imageUuid)) return null;
+
+ cache_.set(cacheKey, { status: 'loading' });
+ loadImageFromPath(path).then(img => {
+ cache_.set(cacheKey, {
+ status: 'loaded',
+ data: img ? {
+ tileWidth,
+ tileHeight,
+ orientation: 'orthogonal',
+ layers: [],
+ tilesetImage: img,
+ tilesetColumns,
+ } : null,
+ });
+ notifyListeners();
+ });
+ return null;
+}
+
+export function findParentTilemapSource(
+ entities: readonly { children: number[]; components: { type: string; data: unknown }[] }[],
+ childId: number,
+): string | null {
+ for (const entity of entities) {
+ if (!entity.children?.includes(childId)) continue;
+ const tmComp = entity.components.find(c => c.type === 'Tilemap');
+ if (!tmComp) continue;
+ const source = (tmComp.data as Record<string, unknown>).source as string ?? '';
+ if (source) return source;
+ }
+ return null;
+}
+
export function clearTilesetCache(): void {
cache_.clear();
imageCache_.clear();
diff --git a/editor/src/panels/hierarchy/CreateTilemapDialog.ts b/editor/src/panels/hierarchy/CreateTilemapDialog.ts
new file mode 100644
index 000000000..3a6d73588
--- /dev/null
+++ b/editor/src/panels/hierarchy/CreateTilemapDialog.ts
@@ -0,0 +1,204 @@
+import type { Entity } from 'esengine';
+import { Dialog } from '../../ui/dialog/Dialog';
+import { showAssetPicker } from '../../ui/asset-picker';
+import { getAssetLibrary } from '../../asset/AssetLibrary';
+import { loadImageFromPath } from '../../gizmos/TilesetLoader';
+import { getInitialComponentData } from '../../schemas/ComponentSchemas';
+import type { HierarchyState } from './HierarchyTypes';
+
+const DEFAULT_TILE_SIZE = 32;
+const DEFAULT_MAP_WIDTH = 20;
+const DEFAULT_MAP_HEIGHT = 15;
+
+interface TilemapConfig {
+ textureUuid: string;
+ tileWidth: number;
+ tileHeight: number;
+ tilesetColumns: number;
+ mapWidth: number;
+ mapHeight: number;
+}
+
+export async function showCreateTilemapDialog(
+ state: HierarchyState,
+ parent: Entity | null,
+): Promise<Entity | null> {
+ const config: TilemapConfig = {
+ textureUuid: '',
+ tileWidth: DEFAULT_TILE_SIZE,
+ tileHeight: DEFAULT_TILE_SIZE,
+ tilesetColumns: 1,
+ mapWidth: DEFAULT_MAP_WIDTH,
+ mapHeight: DEFAULT_MAP_HEIGHT,
+ };
+
+ let loadedImage: HTMLImageElement | null = null;
+ let previewCanvas: HTMLCanvasElement | null = null;
+ let columnsInput: HTMLInputElement | null = null;
+
+ const content = document.createElement('div');
+ content.style.cssText = 'display:flex;flex-direction:column;gap:12px;';
+
+ content.innerHTML = `
+ <div class="es-dialog-field">
+ <label class="es-dialog-label">Tileset Image</label>
+ <div style="display:flex;gap:4px;align-items:center;">
+ <input type="text" class="es-dialog-input es-tilemap-image-name" readonly placeholder="Select image..." style="flex:1;">
+ <button class="es-btn es-tilemap-browse-btn" style="min-width:60px;">Browse</button>
+ </div>
+ </div>
+ <div class="es-dialog-field" style="display:flex;gap:12px;">
+ <div style="flex:1;">
+ <label class="es-dialog-label">Tile Width</label>
+ <input type="number" class="es-dialog-input es-tilemap-tw" value="${DEFAULT_TILE_SIZE}" min="1" max="512" step="1">
+ </div>
+ <div style="flex:1;">
+ <label class="es-dialog-label">Tile Height</label>
+ <input type="number" class="es-dialog-input es-tilemap-th" value="${DEFAULT_TILE_SIZE}" min="1" max="512" step="1">
+ </div>
+ <div style="flex:1;">
+ <label class="es-dialog-label">Columns</label>
+ <input type="number" class="es-dialog-input es-tilemap-cols" value="1" min="1" max="256" step="1">
+ </div>
+ </div>
+ <div class="es-dialog-field" style="display:flex;gap:12px;">
+ <div style="flex:1;">
+ <label class="es-dialog-label">Map Width (tiles)</label>
+ <input type="number" class="es-dialog-input es-tilemap-mw" value="${DEFAULT_MAP_WIDTH}" min="1" max="1000" step="1">
+ </div>
+ <div style="flex:1;">
+ <label class="es-dialog-label">Map Height (tiles)</label>
+ <input type="number" class="es-dialog-input es-tilemap-mh" value="${DEFAULT_MAP_HEIGHT}" min="1" max="1000" step="1">
+ </div>
+ </div>
+ <div class="es-dialog-field">
+ <label class="es-dialog-label">Preview</label>
+ <div class="es-tilemap-preview-wrap" style="height:120px;overflow:auto;background:#1a1a1a;border:1px solid var(--border-color, #333);border-radius:4px;display:flex;align-items:center;justify-content:center;">
+ <canvas class="es-tilemap-preview-canvas" style="display:none;"></canvas>
+ <span class="es-tilemap-preview-placeholder" style="color:#666;font-size:12px;">Select a tileset image to preview</span>
+ </div>
+ </div>`;
+
+ const imageNameInput = content.querySelector('.es-tilemap-image-name') as HTMLInputElement;
+ const browseBtn = content.querySelector('.es-tilemap-browse-btn') as HTMLButtonElement;
+ const twInput = content.querySelector('.es-tilemap-tw') as HTMLInputElement;
+ const thInput = content.querySelector('.es-tilemap-th') as HTMLInputElement;
+ columnsInput = content.querySelector('.es-tilemap-cols') as HTMLInputElement;
+ const mwInput = content.querySelector('.es-tilemap-mw') as HTMLInputElement;
+ const mhInput = content.querySelector('.es-tilemap-mh') as HTMLInputElement;
+ previewCanvas = content.querySelector('.es-tilemap-preview-canvas') as HTMLCanvasElement;
+ const placeholder = content.querySelector('.es-tilemap-preview-placeholder') as HTMLElement;
+
+ function updateColumns(): void {
+ if (loadedImage && config.tileWidth > 0) {
+ config.tilesetColumns = Math.max(1, Math.floor(loadedImage.naturalWidth / config.tileWidth));
+ if (columnsInput) columnsInput.value = String(config.tilesetColumns);
+ }
+ }
+
+ function renderPreview(): void {
+ if (!previewCanvas || !loadedImage) return;
+ const ctx = previewCanvas.getContext('2d');
+ if (!ctx) return;
+
+ previewCanvas.style.display = 'block';
+ placeholder.style.display = 'none';
+
+ const w = loadedImage.naturalWidth;
+ const h = loadedImage.naturalHeight;
+ const scale = Math.min(1, 300 / w);
+ previewCanvas.width = Math.floor(w * scale);
+ previewCanvas.height = Math.floor(h * scale);
+
+ ctx.imageSmoothingEnabled = false;
+ ctx.drawImage(loadedImage, 0, 0, previewCanvas.width, previewCanvas.height);
+
+ if (config.tileWidth > 0 && config.tileHeight > 0) {
+ ctx.strokeStyle = 'rgba(100, 200, 255, 0.4)';
+ ctx.lineWidth = 1;
+ const tw = config.tileWidth * scale;
+ const th = config.tileHeight * scale;
+ for (let x = tw; x < previewCanvas.width; x += tw) {
+ ctx.beginPath();
+ ctx.moveTo(Math.floor(x) + 0.5, 0);
+ ctx.lineTo(Math.floor(x) + 0.5, previewCanvas.height);
+ ctx.stroke();
+ }
+ for (let y = th; y < previewCanvas.height; y += th) {
+ ctx.beginPath();
+ ctx.moveTo(0, Math.floor(y) + 0.5);
+ ctx.lineTo(previewCanvas.width, Math.floor(y) + 0.5);
+ ctx.stroke();
+ }
+ }
+ }
+
+ browseBtn.addEventListener('click', async () => {
+ const result = await showAssetPicker({
+ title: 'Select Tileset Image',
+ allowedTypes: ['image'],
+ extensions: ['png', 'jpg', 'jpeg', 'webp'],
+ });
+ if (!result) return;
+
+ config.textureUuid = result.uuid ?? '';
+ imageNameInput.value = result.name;
+ dialog.setButtonEnabled(0, !!config.textureUuid);
+
+ loadedImage = await loadImageFromPath(result.relativePath);
+ updateColumns();
+ renderPreview();
+ });
+
+ twInput.addEventListener('input', () => {
+ config.tileWidth = Math.max(1, parseInt(twInput.value) || DEFAULT_TILE_SIZE);
+ updateColumns();
+ renderPreview();
+ });
+ thInput.addEventListener('input', () => {
+ config.tileHeight = Math.max(1, parseInt(thInput.value) || DEFAULT_TILE_SIZE);
+ renderPreview();
+ });
+ columnsInput.addEventListener('input', () => {
+ config.tilesetColumns = Math.max(1, parseInt(columnsInput!.value) || 1);
+ });
+ mwInput.addEventListener('input', () => {
+ config.mapWidth = Math.max(1, parseInt(mwInput.value) || DEFAULT_MAP_WIDTH);
+ });
+ mhInput.addEventListener('input', () => {
+ config.mapHeight = Math.max(1, parseInt(mhInput.value) || DEFAULT_MAP_HEIGHT);
+ });
+
+ const dialog = new Dialog({
+ title: 'New Tilemap Layer',
+ content,
+ width: 420,
+ buttons: [
+ { label: 'Create', role: 'confirm', primary: true, disabled: true },
+ { label: 'Cancel', role: 'cancel' },
+ ],
+ });
+
+ const result = await dialog.open();
+ if (result.action !== 'confirm' || !config.textureUuid) return null;
+
+ const entity = state.store.createEntity('TilemapLayer', parent);
+ const transformData = getInitialComponentData('Transform');
+ state.store.addComponent(entity, 'Transform', transformData);
+
+ const layerData = getInitialComponentData('TilemapLayer');
+ const tiles = new Array(config.mapWidth * config.mapHeight).fill(0);
+ state.store.addComponent(entity, 'TilemapLayer', {
+ ...layerData,
+ texture: config.textureUuid,
+ tileWidth: config.tileWidth,
+ tileHeight: config.tileHeight,
+ tilesetColumns: config.tilesetColumns,
+ width: config.mapWidth,
+ height: config.mapHeight,
+ tiles,
+ });
+
+ state.store.selectEntity(entity);
+ return entity;
+}
diff --git a/editor/src/panels/hierarchy/EntityTemplates.ts b/editor/src/panels/hierarchy/EntityTemplates.ts
index be1776640..2aaa3f3ce 100644
--- a/editor/src/panels/hierarchy/EntityTemplates.ts
+++ b/editor/src/panels/hierarchy/EntityTemplates.ts
@@ -71,6 +71,11 @@ export const ENTITY_TEMPLATES: Record<string, EntityTemplate> = {
components: [{ type: 'Transform' }, { type: 'Tilemap' }],
}),
+ TilemapLayer: general({
+ name: 'TilemapLayer',
+ components: [{ type: 'Transform' }, { type: 'TilemapLayer' }],
+ }),
+
Camera: general({
name: 'Camera',
components: [{ type: 'Transform' }, { type: 'Camera' }],
diff --git a/editor/src/panels/hierarchy/HierarchyContextMenu.ts b/editor/src/panels/hierarchy/HierarchyContextMenu.ts
index 151ffe016..9cf73adfb 100644
--- a/editor/src/panels/hierarchy/HierarchyContextMenu.ts
+++ b/editor/src/panels/hierarchy/HierarchyContextMenu.ts
@@ -12,6 +12,7 @@ import { hasAnyOverrides } from '../../prefab';
import { getAssetTypeDescriptor } from '../../asset/AssetTypeRegistry';
import type { HierarchyState } from './HierarchyTypes';
import { instantiateTemplate } from './EntityTemplates';
+import { showCreateTilemapDialog } from './CreateTilemapDialog';
const create = (state: HierarchyState, template: string, parent: Entity | null) =>
() => instantiateTemplate(state, template, parent);
@@ -36,6 +37,7 @@ export function showEntityContextMenu(state: HierarchyState, x: number, y: numbe
{ label: 'Shape', icon: icons.hexagon(14), onClick: create(state, 'ShapeRenderer', entity) },
{ label: 'Particle', icon: icons.star(14), onClick: create(state, 'ParticleEmitter', entity) },
{ label: 'Tilemap', icon: icons.grid(14), onClick: create(state, 'Tilemap', entity) },
+ { label: 'Tilemap Layer', icon: icons.layers(14), onClick: () => showCreateTilemapDialog(state, entity) },
] },
{ label: 'UI', icon: icons.pointer(14), children: [
{ label: 'Canvas', icon: icons.template(14), onClick: create(state, 'Canvas', entity) },
diff --git a/editor/src/panels/tile-palette/TilePalettePanel.ts b/editor/src/panels/tile-palette/TilePalettePanel.ts
index 60cbb0e71..4d5ddae4e 100644
--- a/editor/src/panels/tile-palette/TilePalettePanel.ts
+++ b/editor/src/panels/tile-palette/TilePalettePanel.ts
@@ -1,7 +1,7 @@
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 { getTilesetForSource, getTilesetForImage, findParentTilemapSource, addTilesetLoadListener, type TilesetInfo } from '../../gizmos/TilesetLoader';
import { icons } from '../../utils/icons';
const TILE_RENDER_SIZE = 32;
@@ -159,36 +159,38 @@ export class TilePalettePanel implements PanelInstance {
const entityData = this.store_.getSelectedEntityData();
const entityId = entityData?.id ?? -1;
- if (entityId === this.lastSelectedEntityId_ && this.cachedSource_) return;
+ const newSource = this.resolveSource_(entityData);
+
+ if (entityId === this.lastSelectedEntityId_ && newSource === this.cachedSource_) return;
this.lastSelectedEntityId_ = entityId;
this.isReadOnly_ = false;
- this.cachedSource_ = null;
+ this.cachedSource_ = newSource;
this.cachedInfo_ = null;
- if (entityData) {
+ if (entityData && newSource) {
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;
- }
+ if (layerComp && !this.cachedInfo_) {
+ const parentSource = findParentTilemapSource(this.store_.scene.entities, entityData.id);
+ if (parentSource) {
+ this.cachedInfo_ = getTilesetForSource(parentSource);
+ } else {
+ const layerData = layerComp.data as Record<string, unknown>;
+ const textureUuid = layerData.texture as string ?? '';
+ if (textureUuid && typeof textureUuid === 'string') {
+ const tw = layerData.tileWidth as number ?? 32;
+ const th = layerData.tileHeight as number ?? 32;
+ const cols = layerData.tilesetColumns as number ?? 1;
+ this.cachedInfo_ = getTilesetForImage(textureUuid, tw, th, cols);
}
}
}
@@ -197,14 +199,30 @@ export class TilePalettePanel implements PanelInstance {
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;
- }
+ private resolveSource_(entityData: { id: number; components: { type: string; data: unknown }[] } | null): string | null {
+ if (!entityData) return null;
+
+ const tilemapComp = entityData.components.find(c => c.type === 'Tilemap');
+ if (tilemapComp) {
+ const source = (tilemapComp.data as Record<string, unknown>).source as string ?? '';
+ if (source) return source;
+ }
+
+ const layerComp = entityData.components.find(c => c.type === 'TilemapLayer');
+ if (layerComp) {
+ const parentSource = findParentTilemapSource(this.store_.scene.entities, entityData.id);
+ if (parentSource) return parentSource;
+
+ const layerData = layerComp.data as Record<string, unknown>;
+ const textureUuid = layerData.texture as string ?? '';
+ const tw = layerData.tileWidth as number ?? 32;
+ const th = layerData.tileHeight as number ?? 32;
+ const cols = layerData.tilesetColumns as number ?? 1;
+ if (textureUuid && typeof textureUuid === 'string') {
+ return `img:${textureUuid}:${tw}:${th}:${cols}`;
}
}
+
return null;
}
diff --git a/editor/src/plugins/tilemap.ts b/editor/src/plugins/tilemap.ts
index cf63cbe91..52d8fa61a 100644
--- a/editor/src/plugins/tilemap.ts
+++ b/editor/src/plugins/tilemap.ts
@@ -14,13 +14,12 @@ const TilemapSchema: ComponentSchema = {
const TilemapLayerSchema: ComponentSchema = {
name: 'TilemapLayer',
category: 'builtin',
- hidden: true,
properties: [
{ name: 'width', type: 'number', min: 1, max: 1000 },
{ name: 'height', type: 'number', min: 1, max: 1000 },
{ name: 'tileWidth', type: 'number', min: 1, max: 512 },
{ name: 'tileHeight', type: 'number', min: 1, max: 512 },
- { name: 'texture', type: 'number' },
+ { name: 'texture', type: 'texture' },
{ name: 'tilesetColumns', type: 'number', min: 1, max: 256 },
{ name: 'layer', type: 'number', min: LAYER_MIN, max: LAYER_MAX },
],
diff --git a/sdk/src/scene.ts b/sdk/src/scene.ts
index 6d92db26c..c10df6587 100644
--- a/sdk/src/scene.ts
+++ b/sdk/src/scene.ts
@@ -138,6 +138,11 @@ const COMPONENT_ASSET_FIELDS = new Map<string, ComponentAssetFields>([
{ field: 'source', type: 'tilemap' },
],
}],
+ ['TilemapLayer', {
+ fields: [
+ { field: 'texture', type: 'texture' },
+ ],
+ }],
['TimelinePlayer', {
fields: [
{ field: 'timeline', type: 'timeline' },