garage44.eu/jeroen/cartopolis

logclone: git clone https://garage44.eu/jeroen/cartopolis.git

.. /docs/notes/prim-scripting.md

raw


topic: prim-scripting triggers: [scripting.rs, script_editor.rs, mlua, luau, "script", "sandbox", "fuel", "on_touch", set_geo, sensor, particles, send, on_message, play_sound, loop_sound, prim_sound, SoundName, interact.rs, picking.rs, prim_geo.rs, crates/simulator/content, "PrimDto::scripted", TouchPrim] updated: 2026-10-17

Prim scripts: the API, and what the Luau engine taught

Prims run JavaScript in one Bun process the simulator supervises, one script host thread talking to it (cartopolis_simulator::scripting, tools/script-host). Its design, measurements and traps are javascript-prim-scripts.md; this note holds the API's decisions, which hold for any engine, and what the first engine taught.

Luau, through mlua, one VM per prim, was the engine until 2026-11-16, and for a day the two ran side by side behind script_engine. Then Luau was removed with mlua: the hosted world's 64 scripts were all JavaScript by then, and two engines meant every API call, rule and pack script written twice. Its sections below are history, kept because the question it was chosen on is the one any engine still has to answer.

Why Luau was chosen, and why the choice is not really about the language

Three capabilities decided it, and standard Lua has only two:

So the comparison that decided this was Luau against standard Lua, not against the wider field. Anything proposed to replace it has to answer the same question first: can an over-budget script be suspended and resumed, or only killed?

JavaScript on Bun answers that question by rewriting the script into generators (javascript-prim-scripts.md).

A fuel yield is silently a no-op outside a coroutine (Luau, history)

The single most important thing to know before adding an entry point, because it looks like nothing is wrong and there is no diagnostic anywhere. Found and fixed 2026-08-10.

Luau's lua_isyieldable is nCcalls <= baseCcalls, and only lua_resume raises the base — so a body running under a plain pcall is not yieldable. When the interrupt hands back VmState::Yield there, mlua discards it without error: no log line, no Err, no panic. Fuel accounting therefore appears to be installed and enforces nothing.

Slot::compile ran the author's top-level chunk exactly that way, so while true do end at the top level hung the host thread forever — while the note above, the code comment beside it and the test suite all said it could not. The test survived because it only covered a loop inside on_start, which is resumed and was correctly metered. The consequences compounded in a way worth knowing, because they are what the symptom looks like from outside: the host thread never returns to rx.recv(), HostMsg is unbounded and fed by every scripted prim 20×/s, so the process grows until OOM — and since source is persisted before it runs, a restart replays it and hangs again before any other prim compiles, still logging "scripts loaded" with the full count.

The rule: every path that executes author code must go through a fuel-bounded thread, never pcall. A new entry point is exactly where this comes back, and the sandbox has a second door onto the same problem — Slot::handler uses raw_get because a top-level setmetatable(getfenv(), …) is not something luaL_sandbox prevents.

Two things sandbox(true) does not do (Luau, history)

Measured against mlua 0.12 / Luau, 2026-08-10.

require is a filesystem read primitive, and it is on by default. mlua's Lua::new() wires Luau's require-by-string to an FsRequirer (src/luau/mod.rs — self.globals().raw_set("require", require)), and sandbox(true) does not remove it. "Luau is sandboxed" is a statement about the language; the binding adds capabilities back. Slot::compile strips require (and loadstring) before sandboxing, and sandbox_denies_escape_routes is the test that holds it shut across version bumps. Anything else mlua adds to globals in a future release arrives switched on — re-read that list when bumping.

Luau allocates in ~32 KiB pages, so a small memory ceiling is meaningless. Loading a one-line handler costs 32,720 bytes; a two-line one costs 65,440. Second Life's familiar 64 KiB per-script figure is therefore one or two allocations wide here, and scripts failed to compile with "not enough memory" depending on which side of a page boundary the source landed — a limit whose behaviour changes with whitespace. SCRIPT_MEMORY_BYTES is 256 KiB (eight pages) and is measured from the interpreter's baseline, not from zero: a fresh sandboxed state is ~386 KiB before a line of script exists, and that is the host's cost, not the author's.

The corollary nobody costed up front: one VM per prim is ~386 KiB of floor. A world at its default 200 scripts is ~75 MiB of interpreter. That is affordable and it is also the number that decides whether a world can ever have thousands of scripted prims — it would need a shared VM with per-script environments, which gives up the per-script memory ceiling (the allocator limit is per state).

The API is Second Life's shape, and the catalogue is shared

Calls are flat, plain snake_case globals — set_pos, say, set_timer_event, play_sound — which is Second Life's ll* shape (one global per verb) without a prefix. They were vf-prefixed (vfSetPos) until 2026-10-04; that prefix was the old brand name in front of every call, and it went without aliases, so a script written against it fails on its first call and has to be rewritten. snake_case was chosen to match Luau's own library and stayed through the move to JavaScript, where every stored script and pack already used the names.

Two consequences worth knowing:

What is not in the API is equally deliberate. The realm keeps Math, Date, JSON, Map and Set (realm-runtime.js's allowlist), so there is no frand (Math.random()) and no get_unix_time (Date.now()). A host function that only forwards to the standard library is a second name for one thing.

sleep is a yield, not a host call that blocks: the rewrite turns every handler into a generator, and the scheduler already resumes a paused handler next tick. So sleeping is "yield until the clock says otherwise" — a sleeping script is descheduled by exactly the mechanism that deschedules one which overran. Its clock (get_time) is simulated time for the same reason fuel is counted in steps: two hosts running the same script should agree.

set_pos is durable in y and not in x/z — set_geo is the horizontal one

A prim's horizontal placement is re-derived from its geo anchor (prim_geo::place_geo_prims), so a script's write to position.x/z leaves geo stale: the motion is visible and persists until the map re-anchors or the client reconnects, at which point the prim returns to its anchored spot. Height has no second owner and stays where a script puts it.

The fix, since protocol 20, is not to make set_pos durable but to give the anchor its own call. set_geo(lat, lng) writes the anchor directly — which is the authoritative value, so it survives a re-anchor, a reconnect and a restart — and geo_scale(lat) hands back metres per degree so a script can turn a radius into an offset. The firebird in the firebird content pack flies a 180 m circle with the two of them.

That is a smaller change than the one this note used to propose (move the Mercator projection into cartopolis_core and have the sim rewrite geo from position), and it is better rather than merely cheaper. The projection the client uses is anchored at the map anchor, which is a different frame for every client and moves when any of them teleports; the sim cannot reproduce it and should not try. Naming the geographic coordinate outright means no frame has to be reconciled at all — the same reasoning ADR-029 applied to prim placement in the first place.

The old advice — that the editor's template bobs a prim up and down rather than orbiting it — is why that template is what it is, not a statement that orbiting is impossible.

sensor is the only thing that can see an avatar, and it needed a wire change

An avatar's sim position is metres in its own client's anchored frame. Every client anchors somewhere else and re-anchors when it teleports, so two avatars in two cities both sit near the origin and "is this avatar near that prim?" has no answer in sim space at all. A prim, meanwhile, has carried an absolute GeoAnchor since ADR-029.

So protocol 20 added the other half: ClientIntent.geo, the avatar's own client saying where on Earth it is. The sim keeps it, SimWorld::script_views measures it against each scripted prim's anchor once per tick, and sensor(range) returns the nearest one.

Three consequences worth knowing. The neighbours are pushed with the view, not queried — the host thread holds no reference to SimWorld (that is what keeps a script off the tick's write lock), so a sensor reads a snapshot at most one tick old, exactly as get_pos always has. An avatar whose client has not sent a fix is not seen, which is the honest answer rather than a guessed position. And the range is capped at SENSOR_MAX_RANGE_M however wide a script asks, because the gathering is what costs, not the question.

One prim reaches another only over a channel

Every host call acts on the script's own prim — prim_id is captured by the host and is not an argument — so a button cannot reach the thing it controls. That is the authorisation surface working as designed (there is no argument an author can supply that touches somebody else's object) and it also meant a button was impossible to build.

send(channel, text) and on_message(channel, text, sender) are the way through, with listen(channel) to opt in. Four properties, each chosen against an alternative:

A channel reaches every listening script on the server. It used to be scoped to the sender's region, so that an estate's button could not work its neighbour's door — regions are retired (retired/regions.md) and nothing that survived them divides the world into estates. Bringing that property back means a radius around the sender's GeoAnchor, measured the way sensor already measures, not a new container. MAX_MESSAGES_PER_TICK bounds a sender for a different reason than MAX_COMMANDS_PER_TICK does: a command costs one wire frame, a message costs an event queued on every listener.

Pressing a scripted prim: a click works it, walking up offers to

Until protocol 21 the only way to fire on_touch was the right-click menu's Touch entry — an edit-flavoured developer path that nobody looking for a button finds. Two ways in now, and the order they shipped in is the lesson: the proximity prompt came first and was not enough. The beacon on the Grote Markt proved it when the person it was built for went looking and could not work it.

Both are gated on PrimDto::scripted, the one bit protocol 21 added. The client cannot derive it — source is kept out of WorldSnapshot (below) — and without the gate every crate in the city would offer to be pressed. The prompt matches through the prim's geo anchor, never its Transform: that is a big_space cell-local offset while the avatar's position is absolute anchored world XZ, and comparing the two directly is the frame mistake this whole area keeps making.

Sound is a closed library, and the client measures the distance

play_sound(name, volume?, range_m?), loop_sound(...) and stop_sound() (protocol 33). Four decisions, each against an alternative:

The names were vf-prefixed until the same day this landed; the rename had no aliases, so every stored script written against vfSay and friends fails on its first call until it is rewritten.

The unit of accounting is the world

Capacity (max_prims, max_scripts) is one budget for the server, set in cartopolis.toml. It used to be a column on the region row, on the reasoning that a region is what an operator hands out — no simulator ever ran more than one. Fuel is a per-tick bank spent round-robin with a per-script slice cap, so the cost of a busy world is bounded by the tick, not by the number of scripts in it.

Sourced from Second Life's twenty years of the same problem, and deliberately so: per-object script limits, a memory ceiling per script, and "your script got slower" as the failure mode instead of "your script was killed" are all its answers, and they are answers to a social problem more than a technical one. The one place this deviates is that fuel is measured in interrupt callbacks (a deterministic instruction cadence), not wall-clock — a world's capacity is then reproducible across hosts, and a slow disk cannot make a script look expensive.

Source is not snapshot data

A PrimDto is re-sent to every observer at the tick rate. Script source is an order of magnitude larger than the rest of a prim and is of interest to exactly one person — so it lives in its own table, travels only on GetPrimScript/SetPrimScript, and the editor is the only thing that ever asks. Script output does go to everyone (rate-capped at the host), because the alternative is a per-editor subscription registry that has to be kept in step with disconnects.