Skip to content

Make your own editor panel ​

Add panels, tools, keys, menus and kinds of thing to the map editor for your game. Your panels are built with the same API as the editor's own: they can reach the map, the scene, the camera, the running game and your game's files.

This page follows the Waves panel of the campaign starter (npm create @v12-engine, src/waves-panel.ts): a searchable list of the siege's waves, edited with undo, with where the picked wave comes in drawn in the scene.

Quick start ​

Declare the panel once, as data:

ts
export const wavesPanel: EditorPanelDef = {
	id: 'campaign.waves',
	name: 'Waves',
	icon: 'campaign.wave', // an icon of the game's own, by name
	side: 'right',
	key: 'Shift+KeyW', // opens and closes it
	badge: (editor) => siegeWaves(editor).length, // shown on its icon, closed too
	header: { mount: (element, { editor }) => void element.append(kit.button('Add', () => addWave(editor), { variant: 'ghost', size: 'sm' })) },
	// each wave in the search of everything (Ctrl+K), and alone after `w`: "w boss"
	prefix: 'w',
	search: (editor) => siegeWaves(editor).map((wave, index) => ({ id: String(index), label: `Wave ${index + 1}`, detail: describe(wave) })),
	mount
}

Then ship it as an extension and give it to your editor scene:

ts
export const campaignEditor = defineEditorExtension({ id: 'campaign', name: 'The campaign', panels: [wavesPanel], icons: editorIcons })
export const editor = editorScene({ id: 'editor', name: 'Map editor', game, extensions: [campaignEditor] })

The panel's icon is now on the right rail; Shift+W opens it. mount(element, editor, panel) draws it into an element with any HTML or framework; or give component, a Solid component given { editor, panel }.

Keep state and talk to other panels ​

ts
function mount(element: HTMLElement, editor: EditorClient, panel: EditorPanel): void {
	// kept in this browser with the panel, there again next time it opens
	const picked = panel.state('picked', 0)
	// the kit's search field: Ctrl+F or / in the panel
	const filter = panel.filter({ placeholder: 'Find a wave: skeleton, 3, boss' })
	const pick = (wave: number) => {
		picked.set(wave)
		editor.bus.emit('campaign.wave.picked', { wave }) // other panels hear it
		draw()
	}
	panel.provide({ pick }) // others call editor.panels.api('campaign.waves')?.pick(3)
	panel.onReveal((id) => pick(Number(id))) // a search entry was picked
}

Type your events and offers by declaration merging, so emit, on and api know their data:

ts
declare module '@v12-engine/editor' {
	interface EditorEvents {
		'campaign.wave.picked': { wave: number }
	}
	interface EditorPanelApis {
		'campaign.waves': { pick(wave: number): void }
	}
}

A value two panels both follow is editor.shared(key, initial) (typed by EditorSharedValues).

Edit a game file with undo ​

The waves are the game's file src/campaign/waves.json (a defineGameFile listed in Rules.files). Make each change a step of the editor's history, so Ctrl+Z undoes it with the map's steps and Ctrl+S saves it with the map:

ts
function change(editor: EditorClient, name: string, make: (waves: Wave[]) => void, merge?: string): void {
	const was = copy(siegeWaves(editor))
	const next = copy(siegeWaves(editor))
	make(next)
	const put = (waves: Wave[]) => {
		// the editor's game and the game played here play them at once
		editor.registry.setFile(wavesFile, waves)
		editor.world?.registry.setFile(wavesFile, copy(waves))
		void editor.files.write('campaign/waves.json', waves)
	}
	// steps with the same `merge` one after another are one step (a number dragged)
	editor.history.step({ name, merge, do: () => put(next), undo: () => put(was) })
}

editor.files.watch tells the panel when the file changes (an undo, or a change on disk), so it can draw again.

Draw in the scene ​

What a panel draws is hidden while it cannot be seen and removed when it closes. It draws with lines over the map (WorldLines: line, circle, box), made again when what it says changes:

ts
panel.draw(
	(lines) => {
		const entry = entryOf(editor)
		if (!entry) return
		const middle = { x: entry.x, y: editor.doc.terrain.heightAt(entry.x, entry.z) + 0.3, z: entry.z }
		lines.circle(middle, 2, [1, 0.75, 0.3], { width: 3 })
	},
	{ again: (change) => change.parts.has('points') } // made again when points change
)
panel.frame((dt) => spin(dt)) // each frame, while the panel shows

Ask for a click in the scene ​

ts
panel.pick({
	hint: 'Click where the waves come onto the map',
	pick: ({ ground }) => ground && editor.edit((map) => map.markers.setPoint(entry.id, ground), 'Move where the waves come in')
})

The click goes to the panel instead of the picked tool; Escape cancels. To drag what the panel drew, add grab (and grabs to say whether a press would be taken):

ts
panel.pick({
	many: true,
	pick: () => {},
	grabs: (at) => !!handleUnder(at),
	grab: (at) => {
		const handle = handleUnder(at)
		if (!handle) return false
		return { move: ({ ground }) => ground && moveIt(handle, ground), drop: () => keepAsOneStep(), cancel: () => putBack() }
	}
})

To show your own fields in the Inspector's place: editor.inspect({ id: 'campaign.waves', component: WaveFields }). For a view of its own: panel.viewport(canvas, { camera }).

Show what the game played here is doing ​

ts
const drawLive = () => {
	const world = editor.world
	live.textContent =
		editor.playing() && world ? `Played here: wave ${wavesOf(world).wave + 1} of ${siegeWaves(world).length}` : `${siegeWaves(editor).length} waves`
}
panel.on('play.tick', drawLive)

editor.playing() says whether the map is played here, editor.played is the game's client, and editor.world the running world (for a game played in the page). Act as a player would, through editor.played.session.send(command). A panel with when: 'play' exists only while playing.

Add a cinematic lane ​

A lane of your own is edited in the Cinematic panel like the built-in ones. The starter's waves lane calls a wave in at a moment of a cinematic:

ts
import { type Clip, defineLane } from '@v12-engine/client'

export interface WaveClip extends Clip {
	wave?: number
}

export const waveLane = defineLane<WaveClip>({
	kind: 'campaign.wave',
	name: 'Waves',
	length: () => 0,
	// the rules decide: a command, so every screen and the replay agree
	run: (cut, _item, from) => void (from === 0 && cut.stage.send?.(nextWave.make({}))),
	editor: {
		color: '#d9a441',
		icon: 'campaign.wave',
		moment: true, // a new one has no length
		fields: [{ key: 'wave', kind: 'number', label: 'Wave', optional: true, step: 1, min: 1 }],
		label: (item) => (item.wave ? `wave ${item.wave}` : 'next wave'),
		// said in Problems, the click opening the item
		check: (item) => (item.wave && item.wave > builtWaves().length ? `the siege has ${builtWaves().length} waves, not ${item.wave}` : undefined),
		// drawn in the scene while the Inspector shows the cinematic
		draw(item, at) {
			const entry = at.point(WAR_CAMP)
			if (!entry) return
			const middle = { x: entry.x, y: at.heightAt(entry.x, entry.z) + 0.4, z: entry.z }
			at.lines.circle(middle, at.selected ? 2.5 : 2, at.selected ? [1, 1, 1] : [0.85, 0.64, 0.25], { width: at.selected ? 4 : 2 })
		},
		inspector: { mount: (element, { items }) => showWhatItBrings(element, items) }
	}
})

The game plays it with lanes: [waveLane] on the view; the extension's lanes brings it to the editor (or editor.lanes.add(lane)).

Ship it as an extension ​

ts
export const campaignEditor = defineEditorExtension({
	id: 'campaign',
	name: 'The campaign',
	panels: [wavesPanel],
	icons: editorIcons,
	search: editorSearch,
	lanes: [waveLane]
})

// the editor scene declares it
export const editor = editorScene({ id: 'editor', name: 'Map editor', game, extensions: [campaignEditor] })

editor.extensions.add(extension) does the same in code and gives back a function that removes all of it. An npm package or a mod's editor part is an extension too. Save its module while the editor is open (npm run dev) and the new version takes over at once: open panels stay open with their state. The extension must be exported for that.

Add a tool ​

A tool goes on the strip in the scene with its icon and key, and is handed the pointer and keys while it is picked:

ts
class RoadTool implements Tool {
	readonly cursor = 'target'
	constructor(private readonly host: ToolHost) {}
	pointerDown({ ground }: ToolPointer): void {
		if (!ground) return
		const road = this.host.editor.map.paths.find((path) => path.name === 'road')
		// as wide as the tool is set to, on the bar over the scene
		if (!road) this.host.editor.markers.addPath([ground], 'road', Number(this.host.tool.optionsOf('td.road').width))
		else this.host.editor.markers.setPath(road.id, { points: [...road.points, ground] }, 'Lay the road on')
		this.host.changed()
	}
}

export const editorTools: GameToolDef[] = [
	{
		id: 'td.road',
		name: 'Road',
		icon: 'tool.path',
		key: 'KeyO',
		options: [{ id: 'width', name: 'Width', kind: 'number', default: 3, min: 1, max: 8, step: 0.5 }],
		// keys that count while it is picked, asked before the editor's
		actions: [{ id: 'td.road.back', label: 'Take the last point of the road away', group: 'The tower defense', default: ['Backspace'], run: (editor) => takeLastPoint(editor) }],
		make: (host) => new RoadTool(host)
	}
]

Tools change the map through host.editor, a MapEditor, so they undo like the rest. Keep editor code in your app's editor files (the starter's src/campaign-editor.ts), not in your rules: the rules run where there is no screen.

Add a kind of thing ​

For things none of the engine's kinds describe (ground kept clear, spawners, patrol posts), declare a kind. It gets a tool, a Hierarchy group, Inspector fields, selection, copy and paste, names, undo and search:

ts
export const editorKinds: MapKindDef[] = [
	{
		id: 'td.clearings', // also where its things are kept: GameMap.data['td.clearings']
		name: 'Clearing',
		hint: 'Ground kept clear: no tower is built within its reach',
		icon: 'tool.circle',
		key: 'KeyK',
		color: [1, 0.6, 0.35],
		fields: [{ id: 'radius', name: 'Reach', kind: 'number', default: 3, min: 1, max: 12, step: 0.5 }],
		reach: 'radius' // drawn as a ring this far
	}
]

Your rules read them:

ts
export const keepClearingsFree = defineHook({
	hook: 'canPlace',
	id: 'keepClearingsFree',
	run(world, event) {
		for (const clearing of world.map.things('td.clearings')) {
			const reach = Number(clearing.data?.radius ?? 3)
			if (dist(clearing, event.site) < reach) event.cancelled = true
		}
	}
})

A kind can also give create(at, editor) (what a new one starts with; null refuses the place), draw(thing, { selected, color }) and label(thing).

Add an Inspector section, a menu line and a search source ​

ts
export const editorInspector: InspectorSectionDef[] = [
	{
		id: 'td.road',
		title: 'The road',
		when: (selected) => selected.paths.some((path) => path.name === 'road'),
		rows: (selected) => {
			const road = selected.paths.find((path) => path.name === 'road')!
			return [
				{ label: 'Length', value: `${Math.round(new Path(road.points, road.width).length)} cells` },
				{ label: 'Points', value: String(road.points.length) }
			]
		},
		actions: ['td.road.look'] // a button for that action, with its key
	}
]

export const editorIcons: Record<string, EditorIcon> = { 'td.road': '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" …>…</svg>' }

export const editorMenus: EditorMenu[] = [{ id: 'map', label: 'Map', items: [{ id: 'td.road', action: 'td.road.look', icon: 'td.road' }] }]

export const editorSearch: SearchSource[] = [
	{
		id: 'td.road',
		name: 'The road',
		entries: (editor) =>
			roadOf(editor.map).points.map((point, index) => ({
				id: `point:${index}`,
				label: `The road's point ${index + 1}`,
				kind: 'The road',
				run: (client) => client.framing.focusOn(point)
			}))
	}
]

Right-click menu lines come from editor.contextMenus.for(kinds, provider, { order }), and Inspector buttons from editor.inspector.addActions(kinds, actions). Keys are on Getting around.

Add a theme ​

ts
export const editorThemes: EditorThemeDef[] = [
	{ id: 'td-dusk', label: 'Tower defense: dusk', base: 'classic', tokens: (classic) => ({ accent: '#7fd4ff', edge: '#4a8fb0', ring: '#7fd4ff' }) }
]

It appears in the editor's settings after the editor's own themes.

Set the palette, eraser and heights ​

What Place offers and what the brushes allow is your game's to say, in Rules.editor (MapEditorDef):

ts
editor: {
	palette: (registry) => [
		{ name: 'Towers', types: registry.units.all().filter((def) => def.kind === 'building') },
		{ name: 'Invaders', types: registry.units.all().filter((def) => def.bounty), owner: MAP_CREEPS, camps: true }
	],
	heights: [0, 8]
}
FieldWhat it isDefault
paletteGroups of types; each group's owner and campsdefaultPalette: units, heroes, buildings, resources, creeps
eraseWhat the eraser can be set to, { id, name, takes(def) }DEFAULT_ERASE: units, buildings, resources, trees
reach(def)What the starts must be able to walk toResources two cells or bigger, not trees
heightsLowest and highest ground-4 to 16
playersFixed players, or open slotsOpen slots
check, silenceYour own map checks; rules silenced for every mapSee Debug views
fieldsMap fields (defineMapField)See Placing

When it goes wrong ​

A panel that throws (as it is drawn, in a frame hook, a listener or a click) shows the error over itself with Reload, and the Console has it with the panel's id. The editor keeps working. A closed panel costs nothing: no hooks, listeners, drawing or search entries.

Reference ​

What you can add ​

WhatDeclaredIn code
A panelpanels: [{ id, name, icon, side, component | mount, badge, header }]editor.panels.add(def), remove(id), open(id), handle(id)
Events between panelsEditorEvents, mergededitor.bus.on(name, listener), once, emit; panel.on
What a panel offersEditorPanelApis, mergedpanel.provide(api); editor.panels.api(id), panels.when(id, { open })
A shared valueEditorSharedValues, mergededitor.shared(key, initial, { keep })
Search entriespanels[].search(editor), prefixpanel.onReveal(listener); editor.panels.reveal(id, entry)
Drawing in the scenepanel.draw(make, { again, pickable, lit, onTop, hidden }), panel.frame(run); editor.screen.onFrame(run)
The game played herepanels[].when: 'play'editor.playing(), editor.played, editor.world; play.started, play.stopped, play.tick
An undo stepeditor.history.step({ name, do, undo, merge }), begin, commit, cancel
A view of its ownpanel.viewport(canvas, { camera | own, scale, every, always, maxWidth })
A click in the scenepanel.pick({ pick, hover, many, hint, cursor, cancelled, grab, grabs }); editor.screen.pickFromScene
Everything, as oneextensions: [defineEditorExtension({ ... })]editor.extensions.add, remove(id), get, has, list
A tooltools: [{ id, name, icon, key, actions, options, panel, make }]editor.tools.add(def), editor.setTool({ kind: 'custom', id }), tool.setOption
A keyactions: { add, hide, change }editor.keys.define, forget, bind, press, key
An Inspector sectioninspector: [{ id, title, when, rows, actions, before }]editor.inspector.add(section, { before }), remove(id), restore(id)
A kind of thingkinds: [{ id, name, icon, key, color, fields, reach }]editor.kinds.add(kind), remove(id); editor.placeThing(kind, at)
An iconicons: { 'td.road': '<svg…>' }editor.setIcon(name, icon)
A menu or menu linesmenus: [{ id: 'map', label: 'Map', items: [...] }]editor.menus.add('map', line, { before }), addMenu, remove
A search sourcesearch: [{ id, name, prefix, fuzzy, entries(editor) }]editor.search.add(source, { before }), remove(id)
A starting layoutlayout: 'objects', or { id, name, docked }editor.dock.layouts.use(id), editor.dock.setLayout(kept)
A layout in Window › Layoutsan extension's layoutseditor.layouts.add(preset), remove(id)
A themethemeseditor.addTheme(theme), removeTheme(id), themeLook()
Areas of the map editorEditorOptions.mapAreas, an extension's areaseditor.addMapArea(def); editor.doc.area('td.waves')

An extension also takes setup(editor), run once everything is in, giving back what undoes it. One with the same id replaces the earlier.

Panel definition (EditorPanelDef) ​

FieldWhat it is
id, name, iconIts id, title and rail icon (EditorIcon: a component, SVG markup, or a picture URL)
sideWhich rail (right by default)
keyOpens and closes it (the action toggle-<id>; open-<id> opens it)
component, mountWhat draws it
badge(editor)On its icon: a count, words, or { value, tone, tip }
headerButtons in its title bar
search, prefix, searchFuzzyIts entries in the search of everything; searchFuzzy: false where a typo must not find them
when'edit' or 'play': only then
over, size, minSize, maxSizeOpen over the scene; its size
frame: 'bare'No padded box
help, docsThe ? text, and a docs path under EditorOptions.docs (editor/play#use-cheats); F1 opens it

The panel's handle (EditorPanel) ​

MemberWhat it does
state(key, initial)A value kept in this browser per game and panel
filter()The panel's search field (<filter.Field /> or filter.element()); filter.find(items, keys) matches, a typo's nearest last (filter({ fuzzy: false }) takes the words as typed); filterBy keeps the list's order
provide(api), on(name, listener)Offer functions; listen on the bus, removed with the panel
title(), setTitle, badge(), setBadgeIts tab and icon
shown(), onShown, size(), focus(), close(), onCloseWhether it can be seen; its room; closing
draw, frame, pick, viewportThe scene
failed(error, where), guard(where, run)Report or contain a failure (PanelFailure)

What the editor tells panels ​

editor.changes is a signal per part of the editor (EditorChangeKind: map, selection, tool, status, prefs, view, dock, registries, data, inspected, assets, dialog, files, play): changes.of('map', 'selection') reruns a Solid computation, changes.on(['map'], listener) outside Solid. editorParts.follow(editor, 'map') reads the editor that way.

The bus's own events: selection (EditorSelected), map.changed (MapChange: parts, how, operation), tool, file.opened, file.saved, undo, redo, play.started, play.stopped, play.tick, panel.opened, panel.closed. Without a screen, MapEditor.onOperation(listener) and mapChangeOf(operation, how).

Building blocks ​

  • Lists: ListPanel of @v12-engine/client/kit (keyboard, search, paging, Enter, Delete, F2, reorder, menu); createReorder for rows of your own; SearchSelect for long selects.
  • Search: the kit's, one for every list (@v12-engine/client/kit). createSearch(items, { keys: [{ name: 'name', weight: 3 }, 'id', { name: 'description', words: true }], threshold, limit }) keeps an index and gives search(query) → hits with a rank (0 exact, 1 prefix, 2 word starts, 3 somewhere, 4 and up nearly: a typo, flsh finds Flash) and the letters that matched; fuzzyBy(items, query, keys) for one search; rankBy and filterBy as before, a typo's nearest last (or, for filterBy, only when nothing else is found); Highlight marks the letters in a row (<Highlight text={label} query={filter()} />, kit.highlight in plain DOM). A search source's fuzzy: false and a filter's fuzzy: false take the words as typed.
  • Fields: editorRows (NumberRow, ChoiceRow, TextRow, ToggleRow, SliderRow, Fold…), FieldGroup, GroupedFields, SearchedFields, FieldFilter, filterFields. Fields with the same group sit two a line.
  • Drops: assetDrop(kinds, set) for files, outlineDrop for rows of the Hierarchy.
  • Tooltips: data-tip on a control, tip on the kit's Button. Every control of the editor's own panels has one (a test checks it).
  • Icons: Lucide's (import Flame from 'lucide-solid/icons/flame'), the editor's own in EDITOR_ICONS, drawn with <Icon name='…' />.
  • The editor's own panels are built the same way (EDITOR_EXTENSION; their info is EDITOR_PANELS), from what @v12-engine/editor exports: editorParts, WorldEntities, WorldInspector, ModelStage, lookSettings, LogConsole, PerfList and more (see the API reference).
  • The dock: editor.dock.open(id), close, toggle, stateOf(id), pin(id, pinned), float(id), move(id, side), layout(), setLayout(), reset(), layouts.save(name).