The API, group by group
This part covers what each group is for and the rules that matter when using it. Each section links to its page in the API reference, which has every call's signature, options and further examples; the examples here are the ones the reference does not have.
The examples are written as playground snippets, with api already defined. In a plugin
the same lines go inside activate(api). Core concepts has the rules
that hold for every group.
api.document#
The open map as a whole.
- Reading:
isOpen(),info()(name, size, tileset, whether modified or view-only),history()(the undo and redo labels), andscenario()for the whole parsed map, read-only. - Writing:
editandupdate(see The three kinds of write), andundo()/redo(). - Files:
open,create,save,saveAs,close,export(the map as aFile, the way Save writes it, ready to upload) andrenderImage(a PNG). - Testing a built map:
test(bytes, fileName, { launch })hands bytes of your own, such as a map your plugin built, to Tools ▸ Test Map. On the desktop the game is started whenlaunchis true (the user's preference when left out). In a browser the file goes into the test folder the user picked; with none picked it answers null and never downloads. - Whole-map changes:
resizeandchangeTileset. Each is one undo step, as the editor's own dialogs are; on a shared map they clear everyone's undo history instead. - Several open maps:
id(),list()andactivate(id); see Several maps. - Files inside the archive:
extraslists, reads and writes files stored next to the scenario (list,get,set,remove). Keep yours in a folder of your own (my-plugin\notes.json); they are written on the next Save. - Files no name reaches:
archive.unreachable()counts the archive's members that neither a file list nor anything in the map names. Save writes them back as they were stored; the game never opens them, and on a protected map they are mostly decoys.archive.dropUnreachable({ asOpened })leaves them out of the next save, and itsundo()puts them back.
Reading, and a file of the plugin's own that travels with the map:
const info = api.document.info();
if (info) api.log(`${info.name}: ${info.width} × ${info.height}, ${info.tileset}${info.modified ? ", unsaved changes" : ""}`);
const name = "my-plugin\\notes.json";
const stored = api.document.extras.get(name);
const notes = stored ? JSON.parse(new TextDecoder().decode(stored)) : { opened: 0 };
notes.opened++;
api.document.extras.set(name, new TextEncoder().encode(JSON.stringify(notes)));
api.log(`runs of this snippet on this map: ${notes.opened}`);
Try itA new map beside the open one, and a picture of it:
if (await api.document.create({ width: 96, height: 96, tileset: "jungle", name: "Sketch", startLocations: 2, into: "new" })) {
const png = await api.document.renderImage({ pixelsPerTile: 4 });
if (png) await api.ui.saveFile(png, "sketch.png");
}
Try itThe open map, written as Save would write it, sent to Test Map:
const file = await api.document.export();
const outcome = file && (await api.document.test(new Uint8Array(await file.arrayBuffer()), file.name, { launch: false }));
api.ui.status(outcome ? `Written to ${outcome.path}` : "No test folder chosen yet.");
Try itapi.document.sections#
The map file as a list of sections, as the game reads it and Save writes it, with unsaved edits already included. Section Explorer is built on it, and Repair uses its helpers.
Reading. list() gives each section's name, offset, size and what the editor knows
about it. bytes(index) is one section's payload, combined(name) what the game uses
when a name is repeated, and file() the whole file.
Writing. write, rename, insert, remove, move and replaceFile. After each:
- The file is parsed again from scratch and becomes the open map, so the change reaches every part of the editor, even for sections it does not understand.
- The undo history and selections are cleared, and the
"document"event fires with reason"replace". - The call returns the parser's
warnings. - Indices shift after an insert or remove, so call
list()again. - The map is marked modified. The exception is
replaceFile(bytes, { asOpened: true }), which takes the bytes as the file that was opened. Use it for a repair made right after"open", so the map does not ask to be saved when nothing the user did changed it. Save still writes the bytes.
Helpers for repairs. required() (the sections this map's revision must have),
defaults(name) (what File ▸ New would write), trailing() (bytes after the last
readable section), chkOf(file) (the scenario inside an .scx / .scm) and
rebuild(names?) (re-encode sections from the editor's model, fixing sizes, repeats and
broken string offsets).
// Sections the map must have and does not, and sections that appear more than once.
const sections = api.document.sections.list();
const present = new Set(sections.map((s) => s.name));
api.log("missing:", api.document.sections.required().filter((name) => !present.has(name)));
api.log("repeated:", [...new Set(sections.filter((s) => s.occurrences > 1).map((s) => s.name))]);
Try itapi.document.buildSteps#
For a plugin that compiles something into the map, such as a script turned into triggers.
A build step runs whenever the map leaves the editor (Save, Test Map and
document.export), so the user keeps one file and keeps editing the unbuilt map.
api.document.buildSteps.add({
id: "compile",
label: "My Compiler",
// Only maps that carry the plugin's source file are built.
applies: () => api.document.extras.get("my-plugin\\main.txt") !== null,
async run({ map, fileName, purpose }) {
api.log(`building ${fileName} (${map.length} bytes) for ${purpose}`);
return map; // an .scx in, an .scx out: return your compiled map here
},
});
Try itapplies()is asked on every save and must be cheap. While it is false, Save is unchanged.rungets the map as Save would write it and returns the built map. Steps from several plugins run one after another, in activation order.purposeis"save","test"or"export".- The editor keeps the unbuilt scenario inside the file and shows that one when the map is opened again, so generated triggers never appear in the trigger list. See Opening and saving maps.
- A step cannot cost the user a save. If
runthrows, the map is saved unbuilt and a notice shows your error message, so write it for the user. Throw a plainErrorfor that: the editor's log keeps it as a warning, since the step worked as meant. Anything else thrown, such as aTypeErroror an error class of your own, is logged as an error, as a bug in the step would be. A Save without it button aborts thesignalthatrunis also given. Test Map stops on an error instead. before({ id, label, applies?, run })runs earlier, on the open map rather than on the bytes, and may usedocument.updateanddocument.edit. TrigScript uses it to write its triggers into the trigger list before every save.builtBy()says which steps built the file the open map came from.
A bare .chk is never built, since it has nowhere to keep the unbuilt copy.
EditTransaction#
What document.edit passes to its function. When the function returns, the transaction
removes doodads the terrain change broke and units the new ground cannot hold (if the
Units palette's Remove stranded units is on), commits and repaints.
- Terrain: read and set tiles (
tileAt,setTile,setTiles), the editor's brushes (stampTerrain,paintIsom,fillArea,placeBlend,replaceTerrain,fillFlat,heal), and the ISOM lattice (rebuildIsom,tilesFromIsom). Most brushes need the tileset graphics.pinkeeps tiles as they are: a pinned tile is skipped by everything here that lays terrain by rule (paintIsom,stampTerrain,fillFlat,fillArea,replaceTerrain,tilesFromIsom,heal), as it is by the editor's own brushes, and still written bysetTile,setTiles,placeBlend,placeBlock,fillPattern,pasteand the doodad calls. - Blocks:
placeBlocklays a block of tiles with its top-left at a tile, as the Tile brush lays a block or a piece;fillPatternrepeats one over an area, as Fill Map does with a block. Holes and cells off the map are skipped; ISOM is left alone. - Objects: units (
placeUnit,canPlaceUnit,addUnits,moveUnits,updateUnits,placeStartLocations, …), sprites, doodads (placeDoodad,placeStretchedDoodad,convertDoodads), locations (addLocation,editLocation; slot 63, Anywhere, is protected), fog (setFog,floodFog, …) andpastefor a wholeClip. - Symmetry:
mirrorandmirrorPointgive the positions Tools ▸ Symmetry would also paint, so your edit can follow the user's setting. note(text)adds a line to the status bar message.
placeUnit places the way the Units palette does but makes no checks; ask canPlaceUnit
first if you want them.
Several operations, one undo entry: a ring of eight marines round the middle of the map, with a location over them.
const info = api.document.info();
if (info) {
const t = api.consts.tile;
const cx = (info.width * t) / 2;
const cy = (info.height * t) / 2;
const result = api.document.edit("Ring of marines", (tx) => {
for (let i = 0; i < 8; i++) {
const x = cx + Math.cos((i * Math.PI) / 4) * 3 * t;
const y = cy + Math.sin((i * Math.PI) / 4) * 3 * t;
if (tx.canPlaceUnit(0, x, y)) tx.placeUnit(0, 0, x, y);
}
tx.addLocation({ left: cx - 4 * t, top: cy - 4 * t, right: cx + 4 * t, bottom: cy + 4 * t }, "The Ring");
});
api.ui.status(`${result.units} marines, ${result.locations} location`);
}
Try itUpdateTransaction#
What document.update passes to its function. The result's sections lists the file
sections actually changed, and changed is false when nothing was.
| Part | What it covers |
|---|---|
tx.triggers, tx.briefing |
The trigger and briefing lists: list, add, replace, remove, move, set, fromText. |
tx.strings |
The string table. intern(text) reuses an identical string or adds one and never overwrites, since an index may be shared. set(index, text) overwrites a slot. |
tx.switches |
Switch names. |
tx.properties |
The scenario's name and description. |
tx.players, tx.forces |
Player slots (type, race, colour, force) and the four forces. |
tx.unitTypes, tx.upgrades, tx.techs |
Unit, upgrade and technology settings, with the game's defaults alongside. |
tx.sounds, tx.cuwp |
WAV slots, and the unit property slots used by Create Unit with Properties. |
tx.setVersion, tx.setTextEncoding |
The map revision and the text encoding. |
A settings change, the way a dialog's OK makes one:
api.document.update("Set up the scenario", (tx) => {
tx.properties({ name: "Last Stand", description: "Hold the ring for ten minutes." });
tx.unitTypes.set(0, { hitPoints: 80, name: "Veteran Marine" });
tx.switches.setName(0, "Gate is open");
});
Try itA trigger built record by record:
const { condition, action, comparison, player } = api.consts.triggers;
api.document.update("Add a countdown", (tx) => {
const trigger = api.triggers.newTrigger([player.Player1]);
const timer = api.triggers.newCondition(condition.CountdownTimer);
timer.comparison = comparison.AtMost;
timer.amount = 30;
trigger.conditions[0] = timer;
const say = api.triggers.newAction(action.DisplayText);
say.text = tx.strings.intern("30 seconds remaining");
trigger.actions[0] = say;
trigger.actions[1] = api.triggers.newAction(action.PreserveTrigger);
tx.triggers.add(trigger);
});
Try itapi.settings#
The same views as the UpdateTransaction parts, for reading without a transaction:
players, forces, unit types, upgrades, techs, sounds, unit property slots, whether a unit
is available to a player (unitAvailable), and version() (revision and text encoding).
Write through document.update.
api.triggers#
Reading triggers and everything needed to show one. Writing is document.update.
- The lists.
list()andbriefing()return copies. A record is 16 conditions and 64 actions of plain numbers. - Showing a trigger.
summarizegives the three lines the trigger list shows,commenta trigger's Comment text, andtextprints and parses the text trigger format.defssays what each condition and action type means and which record field holds each argument. - Making records.
newTrigger,newConditionandnewActionmake blank records.isPreservedandsetPreservedread and set the Preserve Trigger action.triggersFor(list, groups)finds the triggers some player groups own. - Switches and counters.
switchNames()gives every switch's name andswitchUsage()how many conditions and actions mention each.usage()lists every death counter and switch the triggers use, for a plugin that needs counters of its own.epdandaddressOfdo EUD address arithmetic. - What depends on what.
references()says what each trigger reads, writes and names: switches, death counters, memory addresses, locations, the timer, resources, scores, units, strings, sounds, AI scripts and Victory / Defeat / Draw. The Trigger Map plugin draws its whole graph from this one call.- A condition reads. An action writes, or uses something without changing it (the location units are created at, the text a message shows).
- Player groups come resolved to slots, with
approximateset for groups the game settles only while it runs, such as Foes. All Players reaches Players 9–12 in conditions and the unit actions, as the game does, but not as a trigger's owner or in Create Unit, Set Deaths, Set Resources and Set Score, which refuse them.resolvePlayers(group)does that resolution on its own.
To generate triggers, write text. tx.triggers.fromText parses the text format,
interns its strings and resolves names against the open map. That is easier than filling
records field by field, and text with a mistake in it throws with the line and changes
nothing:
const source = `
Trigger("Player 1"){
Conditions:
Bring("Current Player", "Any unit", "Anywhere", At least, 1);
Actions:
Display Text Message(Always Display, "You have arrived.");
Preserve Trigger();
}`;
try {
api.document.update("Add the arrival trigger", (tx) => { tx.triggers.fromText(source); });
} catch (error) {
api.ui.status(String(error)); // a parse error names the line
}
Try itA location or unit the text names has to exist in the map, or the parse fails with the
line number. The trigger reference lists every condition and action in this
form. Use newTrigger / newCondition / newAction to change one field of an existing
record.
Claiming generated triggers. claim(spec) marks a run of the trigger list as made by
your plugin. The Trigger Editor badges and locks those rows and shows your description
with a button that opens your plugin. The Text Trigger Editor fences them off, and Import
Triggers warns before replacing them.
The run is found by content: spec.locate(list) returns { start, count }, or null when
the triggers were edited or removed. Keep a fingerprint of each trigger you generated and
search for them, as TrigScript does. Call refresh() on the handle after regenerating.
claims() lists every plugin's claimed runs.
const mine = new Set<string>(); // fingerprints of the triggers this plugin generated
api.document.update("Generate", (tx) => {
const trigger = api.triggers.newTrigger();
trigger.actions[0] = api.triggers.newAction(api.consts.triggers.action.PreserveTrigger);
mine.add(api.triggers.fingerprint(trigger));
tx.triggers.add(trigger);
});
api.triggers.claim({
label: "the wave generator",
badge: "waves",
locate(list) {
const start = list.findIndex((t) => mine.has(api.triggers.fingerprint(t)));
if (start < 0) return null;
let count = 1;
while (start + count < list.length && mine.has(api.triggers.fingerprint(list[start + count]))) count++;
return { start, count };
},
describe: () => "Made by the wave generator. Change the waves there, not here.",
});
Try itOpen Triggers ▸ Trigger Editor… after running it: the new row carries the badge and is locked, and the form is replaced by your description.

The As text button at the bottom left of the picture is a dialog slot.
api.query#
Read-only questions about the open map.
- What is where:
unitAt,spriteAt,doodadAt,locationAt,unitsIn,unitsOf,startLocations,fogAt. - Placement:
placement(unitId, x, y)gives the Units palette's verdict with a reason in words;doodadPlacementchecks a doodad's ground. - The editor's own tools:
validate()(Check Map's issues),statistics(),find(options)(the Ctrl+F search),strings(),stringUsage(),unusedStrings().
An issue's target from validate() is a unit, location or trigger that view.goTo
accepts, or a settings dialog to open. The problems
panel recipe uses both.
Where a Command Center fits, asked the way the Units palette asks:
const at = await api.ui.pickTile({ prompt: "Click where the Command Center should go" });
if (at) {
const t = api.consts.tile;
const verdict = api.query.placement(106, at.x * t, at.y * t); // 106 is the Terran Command Center
api.ui.status(verdict?.problem ? `Blocked: ${verdict.reason}` : "It fits.");
}
Try itapi.view#
Where the map view is looking, and showing the user something.
zoom/setZoom,visible(),center(x, y),cursorTile(), the View menu's options (flags/setFlags) and grid size. The grid, location names, the two animations and Remastered graphics are remembered between sessions, so a plugin that changes one of them for a moment should set it back.goTo(target)scrolls to a tile, unit, sprite or location and selects it, or opens the Trigger Editor on a trigger ({ kind: "trigger", index }).reveal(rect)glides the view to show an area, and resolvesfalseif the user moved the view first. A plugin following its own work should stop following then.flash(target)briefly highlights tiles, units or locations. Use it for "this just changed" so every plugin's highlight looks the same.
// Visit each start location in turn, until the user takes the view back.
for (const start of api.query.startLocations()) {
const area = { x0: start.tx - 6, y0: start.ty - 6, x1: start.tx + 6, y1: start.ty + 6 };
if (!(await api.view.reveal(area))) break;
api.view.flash({ units: [start.index], kind: "attention" });
await new Promise((next) => setTimeout(next, 800));
}
Try itapi.data#
The game's own tables (units.dat and the rest): hit points, costs, weapons, flags,
graphics. Call load() first; ready() says whether they are already in memory.
Everything is null when the game data was never installed, so degrade instead of throwing.
Values are as the files store them: hit points, for one, are in 256ths.
api.gameData#
Which set of game files the editor uses, the game's own or a mod's, and the plugin side of
Help ▸ Game Data…. The "gameData" event fires on every change.
- Which set.
source()says where the files in use came from,profile()which data set they belong to, andprofiles()lists every set with a copy here. - Managing sets.
install(profile, files, progress)extracts a set from its archives and switches to it,select(id)switches, andremove(id)deletes a set's copy. The game's own archives must be among a mod's files, since a mod only replaces files, unlessfiles.basenames a set whose copy the files are laid over instead.profile.urlsays where the set's makers publish it; a map saved with the set records it. - A set in memory.
attach(profile, read, { hash })draws from a function: every file is asked ofreadfirst, and what it answers null for comes from the set in use. Nothing is stored. After changing whatreadanswers,reload()drops everything decoded and draws the map again — the loop for a plugin that edits the tables or pictures.readgets a second argument:member, the game's own name for the file (arr\units.dat, orrez\stat_txt.tblfortileset/stat_txt.tbl), andunder(path), which reads the set the function was attached over, such as the game's file beneath a mod's.readneed not answerunit/manifest.json: the editor works out from whatreadanswers which tables are in GPTP's.datexlayout and whether the set brings unit names and command card pictures. - The hash.
hashis what a map saved with the set records and what Test Map hands on: the mod's hash, over every file of the set, its plugins and its FireGraft project, never compared with the game's (@scm-js/core'smodHashworks it out). When it is worked out after the files are attached or redrawn,rehash(hash)gives it to the set in use without reading anything again. - Reading files.
read(path)hands over one of the extracted files as bytes, for a plugin that reads the game's formats itself:arr/units.dat,tileset/jungle.cv5,unit/zerg/drone.grp. Paths are the archive's, in lower case with forward slashes, andtileset/manifest.jsonandunit/manifest.jsonlist what was extracted. It answers null for a file the copy does not have.read(path, { under: true })reads the set under a set in memory, without asking its function.storedPath(member)turns the game's name for a file into the path these take. - Races a set adds. A race is a number, and 0 to 7 are the game's; a mod may give its
players others, which no file of the mod names (Races a mod
adds).
races()lists those the set in use declares,{ id, name, letter?, like? }sorted by id (empty for the game's own), andsetRaces(races, id?)declares them for the set in use or the setid, replacing what it had. They are kept with the set's id, so they come back after a new release of the mod and when a set is attached again with the same id; races in the profile given toattachorinstallare kept the same way. The game's own set takes none (setRacesreturns null). Declaring them fires"gameData",names.raceandnames.racesname them, a map saved with the set records them, and Test Map hands them on indataSet.races. In an editor from before this, callsetRaces?.(…)and readsource()?.profile.races ?? [].raceCandidates()resolves to what the set in use suggests,{ names, letters }: the strings itsrez\network.tblhas past the game's own, and the letters other than z, t, p and n with agame\<letter>console.pcxorrez\statbtn<letter>.binof its own, less what is already declared, and nothing for the game's own set. These are hints a person confirms, never names to fill in. A set attached in memory is asked through its function; a stored copy keeps none of these files and gives none.
A mod's files replace the game's in the same formats, so data, tileset, graphics and
names follow them automatically, at whatever width the mod's tables have: data.units()
can hold more than 228 types, names.unitGroups() then ends with the set's own groups,
and graphics.icon pictures the new types where the set has a sheet for them. So take
counts, names and widths from api.data and api.palette rather than the game's numbers
(228 unit types, 130 weapons): the editor's own plugins do, and a mod's tables are wider
and named differently. A plugin written only for the game's own data can check
profile().id ("starcraft") and turn itself off for anything else, or say which of its
parts read the game's own data, as Walkability and Magenta do.
const source = api.gameData.source();
api.log(source ? `${source.profile.name}: ${source.label}` : "still starting up");
for (const set of await api.gameData.profiles()) api.log(`data set ${set.id}: ${set.name}`);
const dat = await api.gameData.read("arr/units.dat");
api.log(dat ? `units.dat is ${dat.length} bytes` : "no game data installed");
Try it// A table editor's loop: draw from the edited tables, and name them once their digest is known.
const edited = new Map<string, Uint8Array>(); // by the game's names, as a mod keeps them
await api.gameData.attach({ id: "draft", name: "Draft" }, (path, file) => (file.member && edited.get(file.member)) ?? null);
// … after an edit:
api.gameData.reload();
api.gameData.rehash(await hashOfMod(edited)); // the mod's hash over every file of the set (core's modHash)
api.consts#
The numbers the map file is written in, so a plugin does not hard-code them: pixels per
tile, the start location and resource unit ids, the unit and sprite flag bits, the
Anywhere location's slot, and triggers, which has every condition and action type,
player group and argument value.
For an argument that takes one of a fixed set of values, api.triggers.defs.choices gives
the values with their labels:
// What each argument of a Set Switch action can be.
const def = api.triggers.defs.action(api.consts.triggers.action.SetSwitch);
for (const arg of def?.args ?? []) {
api.log(arg.label, api.triggers.defs.choices(arg.kind).map((c) => `${c.label} = ${c.value}`));
}
Try itapi.graphics#
The images the map view draws, for your own lists and previews.
- Pictures:
unitImage,spriteImage,tileImageanddoodadImage, in a player's colours where that applies.playerColor(owner)is the colour a player's units are drawn in. - Renders:
renderRectdraws part of the map as a PNG, andrenderClipdraws aClipas the paste preview does. - Icons:
icon(kind, id)is the game's own button picture for a unit type, an upgrade or a technology, as its command card shows it: yellow, or grey or white with{ look: "disabled" }or{ look: "selected" }. It suits a list or a tooltip better than a unit's picture from the map. - Your own GRPs:
grpImage(bytes, frame, { palette, teamColor })draws one frame of a GRP you hold, such as a mod's picture, the way the editor draws a unit: through a tileset's palette ("jungle"; the open map's by default), with the team colour of a player (0 by default,nullfor none).flippedmirrors it andshadowdraws it as a shadow. It resolves with a new canvas, or null when the bytes are not a GRP or there is no game data for the palette.
// A mod's marine in player 2's colour on Ice, beside the game's own.
const mine = await api.gameData.read("unit/terran/marine.grp");
const theirs = await api.gameData.read("unit/terran/marine.grp", { under: true });
for (const bytes of [mine, theirs]) {
const pic = bytes && (await api.graphics.grpImage(bytes, 0, { palette: "ice", teamColor: 1 }));
if (pic) api.log(`a ${pic.width} × ${pic.height} picture`);
}
Try itRules for using them:
- Call
load()first;ready()says what is already in memory. - Unit and sprite images and the icons load lazily, so the first request often returns
null. Call
requestUnit/requestSprite/requestIcons, and redraw inonImageLoaded. - An image is the editor's own cached canvas: draw from it onto a canvas of yours instead of moving it into your page.
- Images are always the classic game's size, even when the user has View ▸ Remastered Graphics on.
- With no game data there are no images. Show the name instead.
api.commands#
Named actions, so a menu item, a hotkey, a context-menu entry and another plugin can all reach the same one.
- An id without a dot is prefixed with your plugin's id (
"convert"becomes"image-to-terrain.convert"); one with a dot is used as is, for a name other plugins can rely on. run(id)runs anyone's command and returns what it returns.list()gives every command registered by every plugin.- Plugins start in no fixed order, so check
has(id)or listen for the"commands"event before calling another plugin's.
// Every command other plugins offer.
for (const c of api.commands.list()) if (c.pluginId !== api.plugin.id) api.log(c.id, c.title, c.enabled ? "" : "(disabled)");
Try itapi.services#
A command is one action; a service is an object to share, such as an account, a server connection or a compiler. One plugin provides it by name and others reach it by that name, whichever starts first.
provide(name, object, { version })holds the object out. Names follow the command rule.watch(name, fn)calls you at once with the object or null, and again whenever the provider arrives, changes or goes. Prefer it toget(name), which answers only for now.has(name)andlist()say what is provided.- The object's shape is up to the provider. Publish a
contract.d.tsin the provider's repository for consumers to import withimport type, and pass aversionso consumers can check it.
The scmjs.dev plugin provides its account this way as scmjs-dev.account, and TrigScript
its build as trigscript.build.
api.sync#
Editing a map together. The editor turns each change to the map into an op (plain JSON) and applies other people's ops in the order a server gives. Your plugin carries them between the two. The scmjs.dev plugin's shared maps are built on this.
This example needs a server of your own, so it has no Try it link:
const session = api.sync.start({
send: (op) => socket.send(JSON.stringify({ type: "op", op })),
onEnd: (reason) => leaveRoom(reason),
onApplied: (report) => { if (report.dropped > 0) showNotice(`${report.dropped} changes no longer applied`); },
});
socket.onmessage = (m) => {
const msg = JSON.parse(m.data);
if (msg.type === "ack") session?.confirm(); // the server accepted our oldest op
if (msg.type === "op") session?.receive(msg.op); // someone else's, in the server's order
};
The server's job is small: put everyone's ops in one order, confirm each to its sender, and pass it on to the others. It never needs to read the map.
The editor does the rest. Your own ops apply at once. If someone else's arrives before
the server has confirmed yours, the editor undoes yours, applies theirs and reapplies
yours, so every editor ends with the same map. Changes find their objects by content, so
an edit to a unit someone else deleted is dropped; onApplied reports how many.
startanswers null when no map is open or another session is already running.current()is the running session, whichever plugin started it.- Incoming ops wait while the user holds a mouse button on the map, while a dialog that
edits the map is open, or while another map is in front (
holding()says which). snapshot()is the map as a file for people joining. It is null while anything is pending.- One session runs at a time. It ends on
stop(), when the map closes, or when the plugin is turned off. If the server rejects one of your ops, end the session: your copy no longer matches.
api.terrain#
Read-only help with the current tileset: the terrains that can be painted (types,
isomTypes), what a tile is (tileInfo, terrainAt, color, heightOf), the ISOM
lattice (diamondAt, diamondsIn), floodRegion and blendCandidates. Also the Terrain
palette's current brush (active / setActive) and Tools ▸ Symmetry (symmetry /
setSymmetry, mirror).
For hand-made terrain: seamStep is the measure View ▸ Seam Overlay draws by and seams
counts the seams it would draw; pinned lists the pinned tiles and handLaid the tiles
the isometric data does not account for, which are the ones worth pinning before a plugin
repaints around them; symmetryShares says how alike the map is to its image under each
symmetry mode, and fairness is the full report for one mode: the small squares that
differ in walking, height and building, where they are, and the resources with no equal
counterpart.
// Widen the picked ramp by three steps and keep it as laid.
const ramp = api.palette.active().doodad;
const [axis] = api.palette.stretchAxes(ramp);
if (axis) {
api.document.edit("Wide ramp", (tx) => { tx.pin(tx.placeStretchedDoodad(ramp, 40, 30, axis, 3)); });
}
// Is a mirrored map the same on both sides?
const report = api.terrain.fairness("h");
if (report && report.unlike > 0) {
api.ui.status(`${report.unlike} small squares differ in ${report.places.length} places`);
}
Try itThe Tile palette's sheet, blocks and pieces are here too. sheet() says how big the
tileset's sheet is and where the groups a data set adds begin; blockFrom takes a
rectangle of it as a block; pieces() is the list the Pieces view shows, pieceAt the
piece Alt+click would pick and blockOf the block that lays a piece; cutPieces runs the
editor's rule over maps of your own. providePieces lists named pieces of yours in the
Pieces view, and provideTypes names flat ground the tileset does not type, for the Rect
brush. active().block is the block the Tile brush lays, and setActive({ block }) arms
it. Named pieces for a tileset puts these together.
Terrain borrowed from another tileset (the Isometric tab's "From other tilesets"):
borrowed() resolves to what the open map's tileset can lay that way, each with an id
for setActive({ terrain }) and tx.paintBorrowed(diamonds, id), which paints it with
the other tileset's own brush and writes the copies. Await it before painting: it reads
the other tileset's files; { scan: true } works the copies out first where nobody has.
provideBorrowTable hands the editor the pairs of tiles a mod meant for a pair of
tilesets, instead of its own match by pictures. Each row of borrowed() also says, in
borders, which of this tileset's grounds the terrain has drawn borders against and where
each came from ("maps", a plugin's id, or the data set's terrain file); where one is
known, tx.paintBorrowed lays the border as the brush does (unless the Drawn borders
switch is off). provideBorderTable gives one: the tiles to lay for each shape of the
border between a borrowed terrain and a ground, and it stands ahead of the terrain file's
and of what maps taught. A mod's terrain.json does what providePieces, provideTypes,
provideBorrowTable and provideBorderTable do, for everyone who adds the mod (Terrain
a mod declares); what a plugin declares is listed ahead
of it.
const roof = (await api.terrain.borrowed()).find((b) => b.source === "install" && b.name === "Roof");
if (roof) api.document.edit("Roof", (tx) => { tx.paintBorrowed(api.terrain.diamondsIn({ x0: 20, y0: 20, x1: 36, y1: 30 }), roof.id); });
// roof.borders: [{ ground: 2, from: "maps" }] — a drawn border against Dirt, learned from maps
Try itCopied terrain (the Isometric tab's "Copied terrain", in the
guide): copies() resolves to the terrains the open map's
tileset holds again at another height with their edge pieces, each with an id for
setActive({ terrain }) and tx.paintCopy(diamonds, id), whether it is complete (else
how many shapes are missing), and the blocks of tiles it can be laid with and the ground
each is drawn for. provideCopies hands the editor one such block, which takes the place
of what the editor found for that terrain and height; a mod's terrain file can carry the
same (copies).
const mud = (await api.terrain.copies()).find((c) => c.complete && c.height === 1);
if (mud) api.document.edit("Mud", (tx) => { tx.paintCopy(api.terrain.diamondsIn({ x0: 20, y0: 20, x1: 36, y1: 30 }), mud.id); });
Try itcheckIsom() measures how well the ISOM lattice matches the tiles. Offer a rebuild when
it reports stale, not merely mismatched: some mismatch (hand-placed tiles, blends)
never goes away.
const report = await api.terrain.checkIsom();
if (report?.stale && (await api.ui.confirm("The isometric data is out of step with the tiles. Rebuild it?"))) {
api.document.edit("Rebuild ISOM", (tx) => { tx.rebuildIsom(); });
}
Try itapi.tileset#
The open map's tileset: id(), name(), isLoaded(), load() and raw() for the
decoded data. load() resolves false when the graphics were never installed, which is a
normal state. load("jungle") fetches another tileset without changing the map, which
graphics.renderClip needs to draw a clip from a map on that tileset.
api.selection#
The marked area (markedArea / markArea), the selected units, sprites, doodads and
locations (by index, with a setter for each), the active layer, and the Layers panel's
locks. Listen for the "selection" event to follow what the user selects.
api.clipboard#
The Cut / Copy / Paste layer, sharing the user's clipboard: copy, cut, paste, clip
/ setClip, and the parts and paste mode. A Clip can be pasted into another map.
capture() returns what copy would take without touching the user's clipboard, for a
plugin that keeps its own clips, like Stamp Library.
// Take the top-left 8 × 8 tiles without touching the user's clipboard,
// and stamp them twice in one undo entry.
const clip = api.clipboard.capture({ rect: { x0: 0, y0: 0, x1: 8, y1: 8 } });
if (clip) {
api.ui.status(api.clipboard.summary(clip));
api.document.edit("Stamp twice", (tx) => {
tx.paste(clip, 8, 0);
tx.paste(clip, 16, 0);
});
}
Try itapi.exchange#
The formats behind File ▸ Import / Export: SCMDraft's .trg trigger files (encodeTrg /
decodeTrg) and the tab-separated strings file (formatStrings / parseStrings).
api.palette#
What the Units, Sprites, Doodads and Fog palettes have picked and what they list, so a
plugin can use "whatever the user chose" without a picker of its own. Paint does this. It
also holds the placement rules (collision, terrain, snap to grid, remove stranded units)
that placeUnit, canPlaceUnit and query.placement follow. The Terrain palette's pick
is terrain.active(). For a doodad, stretchAxes lists the directions it can be
stretched along (a ramp along its cliff, a bridge along and across its deck) and
doodadTwin names the doodad that is its mirror image, the ramp for the cliff running the
other way.
api.names#
The names behind the numbers in a map: units, upgrades, techs, weapons, player types,
races, player groups, trigger types and AI scripts from the game (with a mod's own names
under a mod's data set, see docs/game-data.md), and strings,
locations, switches, players and tiles from the open map. The list forms return
{ value, label }[] for a drop-down. race(value) names the game's eight races and the
races the data set in use declares (gameData.races()), and any other number as Race
and the number; races() lists the game's eight, then the declared ones.
// How many of each unit type the map has, by name.
const counts = new Map<string, number>();
for (const u of api.document.scenario()?.units ?? []) {
const name = api.names.unit(u.unitId);
counts.set(name, (counts.get(name) ?? 0) + 1);
}
api.log([...counts].sort((a, b) => b[1] - a[1]));
// A list form, straight into a drop-down.
const upgrade = api.ui.widgets.select(api.names.upgrades());
Try itapi.text#
StarCraft's text control codes (bytes 0x01–0x1F, written <XX>), from the same table the
String Editor uses. Use it rather than your own copy: the numbering is easy to get wrong.
codes()lists every code;runs(text)splits a string into coloured runs the way the game draws it;plain(text)removes the codes.- Colour carried across lines. The original game reset the colour at each line break;
Remastered carries it on.
bleedingLinesfinds lines that now draw in a colour their author did not choose, andfixBleedingfixes them without changing the text. - Stacked text. The original game drew
Name<12>by Authoras two pieces on one line; Remastered does not.stackedLinesfinds these lines andflattenStackslays them out left to right. The original look cannot be restored, so offer this repair rather than applying it by default.
Repair's string checks are these functions over api.query.strings().
// Every string in the map as the game would draw it, one coloured span per run.
const lines = api.query.strings().flatMap((s) => (s ? api.text.runs(s) : []));
api.ui.dialog({
title: "Strings as the game draws them",
mount(body) {
body.style.background = "#000";
for (const line of lines.slice(0, 40)) {
body.append(api.ui.el("div", {}, ...line.runs.map((run) => api.ui.el("span", { style: { color: run.color } }, run.text))));
}
},
});
Try itapi.ui#
Everything a plugin shows: messages and questions, dialogs, panels, status items, map buttons, preferences pages, dialog slots, map tools, overlays, picks, file types, map views, widgets and tooltips. Putting things on screen covers each in turn. Two calls fit nowhere else:
saveFile(data, fileName)writes a file the way the editor's own exports do, andloadImage/readClipboardImageread pictures.repaint()asks the map view to repaint, for a plugin that changes what its own drawing shows. A transaction repaints by itself.
api.menu / api.contextMenu / api.hotkeys#
References: menu, context menu, hotkeys
Menu items, right-click entries and keys. The rules are in Menus, context menus and hotkeys.
api.i18n#
Translating your plugin the way the editor translates itself: register your catalogues,
then t(text, params) translates. Translating shows the pattern the
project's plugins follow.
tc(context, text, params)translates identical English meant two ways.- Placeholders are a subset of ICU MessageFormat:
{name},pluralandselect. For Korean,{name|을}picks the particle that agrees with the value (을/를, 이/가, 은/는, 과/와, 으로/로). languageis the current language ("en","ko"). The"language"event fires when it changes, so you can relabel what is showing.
api.events#
on(event, fn) listens for a change. Events in Core concepts lists every event
and the rules listeners follow.
api.storage#
get(key, fallback), set(key, value) and remove(key) keep JSON in the browser under
your plugin's id. set returns false when the browser refuses (the quota is a few
megabytes for the whole editor), so a plugin storing the user's work can say so. Users can
see and clear your keys in Preferences ▸ Storage, so never keep the only copy of something
there.
const runs = api.storage.get("runs", 0) + 1;
const kept = api.storage.set("runs", runs);
api.log(kept ? `run number ${runs}` : "the browser's storage is full");
Try itFor data that belongs to one map, use document.extras instead, so it travels with the
file.
api.scope()#
A child of your api that can be removed as a whole. Everything registered through
scope.api (menu items, hotkeys, listeners, panels, dialogs, overlays, map tools,
commands, services) is removed when you call scope.dispose(), and the plugin's own
registrations stay. After the dispose, writes to the map through scope.api are refused,
as they are for a plugin that has been turned off. Scopes can contain scopes, and turning
the plugin off removes every scope it made.
// A mode the user turns on and off: its menu item and listener come and go together.
let mode: ReturnType<typeof api.scope> | null = null;
api.menu.add("Tools", {
label: "Toggle Watch Mode",
run: () => {
if (mode) {
mode.dispose();
mode = null;
return;
}
mode = api.scope();
mode.api.menu.add("Tools", { label: "Watch Mode is on", enabled: () => false });
mode.api.events.on("commit", (e) => api.log("changed:", e.label));
},
});
Try itA scope uses the plugin's own id, storage and name in the log. The API Playground runs each snippet in one. Timers and sockets are not registrations, so clear them yourself.
api.plugin, api.apiVersion, api.log(...)#
Your plugin's id, name and source, the API version, and a logger. log writes to
the browser console and to the editor's View ▸ Debug Console, which users copy into bug
reports, so write lines someone else could follow.
api.log(`${api.plugin.name} (${api.plugin.id}) from ${api.plugin.source}, API ${api.apiVersion}`);
Try it