Map Editor Documentation

Your first sandboxed script

Write JavaScript or TypeScript in the Forge, test it in QuickJS, and remix Aces of Stone or Drop of Stone.

Start here · Page 46 of 53

Open Scripts in the Forge and choose Add script. JavaScript runs as written. TypeScript is compiled before saving; the map keeps both the editable source and the JavaScript that players run. Test Map runs the same sandbox used by published maps.

Keep persistent gameplay state in sos.storage. Global variables and captured closure state are recreated when loading a save; they are suitable for constants and temporary calculations. The storage object, seeded RNG and named timers are restored.

sos.physics.setCircle(id, options) attaches deterministic circle physics to an entity. Positions and velocities use world pixels; walls default to the map bounds. sos.physics.getCircle(id) reads its current position, velocity and contact count, and each contact also arrives as an event (Circle bodies). This solver supports moving circles against static circles and walls; local pegboard maps use the public pegboard controller for richer shapes and moving formations.

sos.lifecycle.onInit(function () {
  sos.storage.waves = 0;
  sos.timers.repeat('wave', 100);
});
 
sos.lifecycle.onTimer(function (event) {
  if (event.name !== 'wave') return;
  sos.storage.waves += 1;
  sos.units.spawn('goblin_wyvern_rider', 2, 1, { x: 20, y: 20 });
});

Timers use simulation ticks. Ordinary RTS maps update at 20 Hz. A map can explicitly override RTS lockstep with a local-only simulation at 20, 30, 60 or 120 Hz. The editor and launch screen display a warning: these maps cannot enter multiplayer or record deterministic RTS replays. Changing RTS update rates also changes tick-based cooldowns and economy pacing.

The sandbox

Code runs inside a pinned QuickJS WebAssembly interpreter, with fixed memory, stack limits and instruction budgets. It cannot directly access the browser, DOM, network, filesystem, real-time clocks, dynamic imports or generated code. Local maps can use the permissioned sos.network.request bridge for declared creator APIs. A runaway script is interrupted by instruction count, not by how fast a player's computer is. Repeated faults disable the script and appear in the test-play debugger.

Use sos.rng for randomness and sos.time.tick() for time. Math.random() uses the same seeded per-script stream. Use sos.storage for persistent game state; ordinary JavaScript closure variables are not saved. Register callbacks at the script's top level so loading the source recreates them. The callback registry is sealed before the match starts.

The Scripts panel lists API calls and inserts their argument shapes. The complete author-facing declarations are available at sos-script-api.d.ts, and the machine-readable API is at script-api.json.

Working with the engine

Read and change units through sos.units, resources through sos.players, and outcomes through sos.game. World scans (ofPlayer, ofType, inRadius) return ascending entity ids and are charged against the script budget. Queries can refuse an oversized scan; check their result before iterating it.

sos.units.get(id) gives a unit's tile as x and y, and its exact point as exactX and exactY, in tiles: a tile's middle is x + 0.5. Use the exact point to aim, or to measure anything finer than a tile. sos.units.positions(units) reads many units at once, as one flat list of exact points ([x0, y0, x1, y1, ...], in tiles), with -1, -1 for a unit that is gone or dead: the cheap way to read a roster you test against every tick. sos.players.get(seat) says who holds a seat: human (a person who has not left the match), alive, team and race, or null for a seat nobody holds. That is how a map tells a person's seat from a computer's, and gives the computer's seats bots of its own.

Every call's arguments go into the engine as JSON and its result comes back as JSON, and that crossing is metered by size on top of the call's own cost (each value going in, each character coming back). So a long list of trigger actions, a big sos.overlay.paint block or sos.units.get in a loop is what eats a tick's 1,600 units, not your own arithmetic. Read a roster with sos.units.positions, and spread heavy work over several ticks with a timer. Each call's own cost is in the declarations.

sos.triggers.run(actions) validates and executes an array of ordinary trigger action nodes through the existing trigger interpreter. This gives scripts the trigger engine's UI, camera, items, abilities, effects and variable actions without a second implementation. Use script timers rather than a wait in an inline action list. The trigger reference gives the action shapes.

sos.hooks.onDamage(fn) can replace a damage amount by returning a finite number. sos.hooks.onOrder(fn) can cancel a command by returning 'cancel'. Hooks are bounded and cannot recursively re-enter the sandbox from an engine call made by another script callback.

sos.lifecycle.onLoad(fn) runs after persistent state is restored. It is read-only: engine mutations are refused and changing stored state disables the script. Use it for checking restored state, not resetting a match.

Input

A map can hear its players' keys and clicks. Each arrives on sos.events.onEvent as an event, and each travels through lockstep like any other command, so every player's copy of the script hears it on the same tick.

sos.input.listen(keys, claim) asks for keys by their browser names ('q', 'Space', 'ArrowUp', in any case), up to 16 keys for all the map's scripts together. Every press and release of one of them arrives as a key-press event with the seat that pressed it, the key (spelt as the game spells it, so 'q' rather than 'Q'), down (true for a press, false for a release), and x and y: where that player's pointer met the ground when the key went down, in tiles. They are null on a release, or when the pointer was off the ground. That point is what a spell aims at.

Call listen at the top level of the script, not inside onInit: the top level runs again when a saved match loads, so the loaded match listens again. A later call replaces the script's list, and an empty list stops it. Without claim, the game's own hotkeys and camera still answer the key, as they do for a trigger. With claim set to true the key is the map's for the match: no hotkey fires and the camera does not move. Escape, Enter, Tab, the F keys and the modifier keys can be heard but never claimed, so a player can always reach the menu. As with a trigger key press, auto-repeat is ignored, typing in a text box never reaches the map, and one player sends at most 20 presses a second.

Two more events come from the HUD. ui-click (seat, frameId) is a click on one of the map's own frames, made with createUIFrame through sos.triggers.run. dialog-button (seat, dialogId, button, counted from 0) is a click on a dialog button. A click counts only when that seat could see that frame or dialog at the time, the same check the uiFrameClicked and dialogButton triggers make.

sos.units.select(seat, units) selects some of a seat's own units on that player's screen, as if they had clicked them: a caster that has just appeared, ready to walk. Only that player's selection changes, and nothing in the match does. Units that are not the seat's are left out, and it returns false if none is.

// Space blinks each player's wizard to the pointer.
sos.input.listen(['Space'], true);
 
sos.lifecycle.onInit(function () {
  sos.storage.casters = {};
  for (var seat = 0; seat < 8; seat++) { // a lobby seats up to eight
    if (!sos.players.get(seat)) continue;
    var ids = sos.units.spawn('human_wizard', 1, seat, { x: 20 + seat * 3, y: 20 });
    sos.storage.casters[seat] = ids[0];
    sos.units.select(seat, ids);
  }
});
 
sos.events.onEvent(function (event) {
  var d = event.data;
  if (event.name !== 'key-press' || d.key !== 'Space' || !d.down || d.x === null) return;
  var caster = sos.storage.casters[d.seat];
  if (caster !== undefined) sos.units.move(caster, { x: d.x, y: d.y });
});

Effects

sos.effects draws a spell's look with none of its rules: no damage, no mana, no cooldown and no caster. The script decides what happens, and the effect only shows it. Spells are named by id, so every shipped spell's look is available, and so is a spell your map clones in Data overrides. The asset catalogue lists the ids.

  • sos.effects.play(spellId, at, seats) plays the spell's effect at a point, in tiles, fractions kept. False for an unknown spell.
  • sos.effects.missile(spellId, from, to, ticks, seats) flies the spell's missile from one point to another over ticks ticks, from 1 to 600. The spell must be one with a missile. It returns the missile's id, the same number on every player's machine, or -1 if refused.
  • sos.effects.stop(id) ends a missile where it is now, because the script decided it hit something. Play the burst with effects.play. False for an id no launch gave, or a missile that has already landed.

seats lists the seats that see it ([0, 2]); leave it out, or pass null, for everyone. Fog hides an effect like any other, and a missile is drawn when either end of its flight is in sight. The map's scripts may start 64 effects and missiles a tick between them, and past that a call is refused.

Two limits to design round. Missiles are drawn in the 3D view only. And effects are not part of the match: they are neither saved nor compared between players, so a missile in flight when a match is saved is not drawn after it loads. Keep what a missile means (where it is going, when it lands, whom it can hit) in sos.storage, and decide its hits there:

// Q throws an arcane missile from the player's caster at the pointer.
// sos.storage.casters maps each seat to its caster, as in the Input example.
sos.input.listen(['q'], true);
 
sos.lifecycle.onInit(function () {
  sos.storage.shots = [];
});
 
sos.events.onEvent(function (event) {
  var d = event.data;
  if (event.name !== 'key-press' || d.key !== 'q' || !d.down || d.x === null) return;
  var me = sos.units.get(sos.storage.casters[d.seat]);
  if (!me || !me.alive) return;
  var from = { x: me.exactX, y: me.exactY }, to = { x: d.x, y: d.y };
  var id = sos.effects.missile('arcane_missile', from, to, 20);
  if (id > 0) sos.storage.shots.push({ id: id, seat: d.seat, from: from, to: to, start: sos.time.tick(), ticks: 20 });
});
 
sos.lifecycle.onTick(function (e) {
  if (sos.storage.shots.length === 0) return;
  var seats = Object.keys(sos.storage.casters);
  var ids = seats.map(function (s) { return sos.storage.casters[s]; });
  var at = sos.units.positions(ids); // one read for every caster
  var flying = [];
  sos.storage.shots.forEach(function (s) {
    var t = (e.tick - s.start) / s.ticks;
    if (t > 1) return; // it landed on nothing
    var x = s.from.x + (s.to.x - s.from.x) * t, y = s.from.y + (s.to.y - s.from.y) * t;
    for (var i = 0; i < ids.length; i++) {
      if (Number(seats[i]) === s.seat || at[2 * i] < 0) continue;
      var dx = at[2 * i] - x, dy = at[2 * i + 1] - y;
      if (dx * dx + dy * dy > 0.36) continue;
      sos.effects.stop(s.id);
      sos.effects.play('arcane_missile', { x: x, y: y });
      sos.units.setHp(ids[i], sos.units.get(ids[i]).hp - 10);
      return;
    }
    flying.push(s);
  });
  sos.storage.shots = flying;
});

Change the land

sos.terrain.set(from, to, kind) turns a rectangle of tiles, corners included, to 'grass', 'dirt', 'shallowWater', 'lava' or 'shallowLava'. sos.terrain.setRing(at, radius, kind, inner) does the same to a ring: every tile whose middle is less than radius tiles from at and at least inner tiles from it. Leave inner out for a whole disc. Both return how many tiles changed, or -1 if the call was refused. The setTerrain trigger action does what set does, over a region. sos.terrain.get(at) names the terrain at a tile ('grass', 'shallowLava', 'rock', 'void' and the rest, all listed in the declarations), or gives an empty string off the map.

Pathing, the minimap and the ground follow at once. One call covers at most 4,096 tiles, counted over its whole rectangle, or over the square round a ring, whether they change or not. To keep every match whole, some tiles never change:

  • Only grass, dirt, stumps, shallow water and lava change. Trees, ore, rock, deep water, the sky and cliffs never do, and neither do cliff heights, ramps or pathing blockers.
  • Land, water and lava never swap under a building, a city lot or a ship.
  • Lava never touches water, the rule the editor keeps, and the two never swap directly: water goes back to land before it can turn to lava.
  • Nothing turns into the sky. Ground can sink into lava, but it cannot fall away into the open air: there is no 'void' kind to set.

Shallow lava is walkable and burns whoever stands in it. Deep lava is a wall, so a ground unit on a tile that turns to deep lava is stuck there until something moves it. An arena that shrinks into the lava should turn its rim to shallow lava, where a caster can still walk out, burning. Paint the platform itself in grass or dirt, because rock never changes.

// Every 15 seconds the platform loses a ring of tiles to shallow lava.
var CENTRE = { x: 32, y: 32 };
 
sos.lifecycle.onInit(function () {
  sos.storage.radius = 12;
  sos.timers.repeat('shrink', 20 * 15);
});
 
sos.lifecycle.onTimer(function (event) {
  if (event.name !== 'shrink' || sos.storage.radius <= 3) return;
  sos.terrain.setRing(CENTRE, sos.storage.radius, 'shallowLava', sos.storage.radius - 1);
  sos.storage.radius -= 1;
});

Walkthrough: a spell brawl from scratch is a whole game built from the calls in Input, Effects and Change the land.

Circle bodies

Every contact a moving circle body makes (sos.physics.setCircle, above) also arrives on sos.events.onEvent as a physics-contact event: unit (the moving body), other (the static body it struck, or 0 for a wall), x and y (the moving body's middle at the contact, in tiles) and speed (how fast it was closing, in world pixels a tick). Use it for a bumper that scores, a wall that hurts, or a pillar that cracks when something is thrown into it. Contacts are sent after the tick's whole solve, in the same order on every machine, up to 64 a tick; past that, bodies still bounce but send no event.

Moving circles still do not collide with each other: only with static circles and the walls. Two casters shoving each other is the script's to work out, from the positions getCircle reads.

Remix the polished examples

The examples below are ordinary custom maps: download one and open it in the Forge with File → Import Map JSON…. Their controller definitions, timing profiles and scripts survive editing, export, Test Map and publishing. Copies include the complete public campaign framework and keep independent player progression. Their own missions, rewards, unlocks and workshop/mastery definitions are editable in the game package.

  • Aces creator example: a scrolling shooter with editable aircraft, weapon profiles, formations, bosses and scoring code.
  • Drop creator example: a pegboard with editable peg layouts, moving formations, bumpers, masters and scoring code.

The Custom-game simulation and controller section in Scripts exposes the map's controller JSON. The public scrolling-shooter and pegboard controllers supply rendering, input, collision and presentation. Aces and Drop use this same controller factory and loader.

Scripts read a plain snapshot with sos.custom.state() and send validated commands with sos.custom.command(name, value):

CommandValueBehaviour
awardScoreA numberAdd or subtract bounded score
setRulesAn objectShooter: scrollSpeed, lives, bombs; pegboard: ballsRemaining, firingImpulse
bullet{x, y, vx, vy, damage, player, color}Add a shooter bullet; coordinates are tiles, velocity is tiles per second, color is six-digit hex
aimAn angle in radiansAim the pegboard cannon
firenullFire a pegboard stone
restartnullRestart the current round
victory / defeatnullEnd the round with a script-defined result

sos.events.onEvent(fn) receives simulation events such as spell-cast, item-used and entity-died, and controller events such as enemy-killed, peg-hit, round-start and sortie-ended. The shipped example scripts use these events to calculate scores. Change that code and the game changes. Players' keys and clicks (Input) and circle-body contacts (Circle bodies) arrive through the same callback.

Pegboard physics uses the same Rapier engine as Drop and is local-only. The separate sos.physics.setCircle(unit, options) API attaches the bounded deterministic circle solver to an RTS entity: it supports circles against static circles and rectangle bounds, without rigid-body stacking, joints or dynamic body pairs. Its velocities and gravity use world pixels per RTS tick.

Debug and publish

Choose Test Map, open Trigger Debug, then select Scripts. It shows each script's gas, errors, strikes, timers, stored state and disabled status. Fix runtime errors before publishing; syntax checks alone cannot prove that a script does what you intended.

Save and publish normally. The validator checks source/compiled agreement and forbidden syntax; players validate the map again when loading. A missing interpreter, unsupported API level or script that fails during loading refuses the match with an error instead of silently removing its logic.