Writing a scenario
A line can be used in two ways. A scenario is one prepared run: a start time, the trains
on the line, events that fire on triggers, and an ending. An operating day is the whole
timetable of a day, looping every 24 hours, and the player picks one service out of it. This
guide builds both against the example mod. Its probefahrt and rangierfahrt scenarios and
its beispieltag day are the worked examples throughout.
You need a mod with a line in it (Building a line). Everything below goes into that
mod’s folder. As everywhere, content is addressed as "<mod>:<file stem>".
1. The scenario file
Section titled “1. The scenario file”A scenario is a RON file in scenarios/. Start with the smallest useful one:
- Create
scenarios/probefahrt.ronand give it anameand adescription. - Name the line it runs on with
line: Some("<mod>:<line>"). A scenario’s positions are indices into one line’s track graph, so it should always say which line that is. A composition works here too.--lineon the command line still wins. - Set the wall clock at the start of the run with
start:. It decides where the sun and moon stand and which season the ground wears. Without it, a run begins at midsummer noon. - Optionally set
weather:to one of the presets (Clear,Cloudy,Rain,Snow, …). The run starts in it, wet rail and all.
( name: "Probefahrt", description: "Short test run on the example line: pull away, then obey the main signal.", start: (year: 2026, month: 8, day: 15, hour: 6, minute: 45, utc_offset: 2.0), player_train: 0, events: [ /* step 3 */ ], line: Some("example:beispielstrecke"),)utc_offset is the local clock’s offset from UT in hours (Germany: 1 in winter, 2 in summer).
Event triggers and Scenario timetables count from the start of the run, not from this clock.
2. Put trains on the line
Section titled “2. Put trains on the line”A scenario may say exactly what stands on the line with consists:. The order of the list
is the order of the train indices, starting at 0. player_train picks the one the player
drives, and every event’s train: and every script address the same list.
rangierfahrt.ron stands a rake of
three machines on the line and the player’s light engine in the siding:
consists: [ ( // 0: three stabled machines at km 3.8, braked, waiting to be collected. number: "Lokzug 77401", vehicles: [(vehicle: "example:br101_afb", count: 3)], at: At(edge: EdgeId(0), s: 3800.0, dir: 1), ), ( // 1: the player's light engine, standing in the siding. number: "Lz 77400", vehicles: [(vehicle: "example:br101_afb", count: 1)], at: Yard("Abstellgleis 1"), ),],player_train: 1,vehiclesnames the stock head first, as stretches of(vehicle, count). A stretch may also pick a livery and a load (variant: Some(1),load: Some(0)).at:is a spawn point.At(edge, s, dir)is where the head stands and which way it faces (dir: 1= towards risings).Yard("…")names one of the line’syards:, a stabling road or a portal (Stabling roads and portals).- A consist without a
timetablestands where it was put with its brakes applied. Withtimetable: Some("<mod>:<name>")the AI drives it, and withshunt:it works a shunt job.prepared: falseputs a cold engine there for the player to wake up.
Leave consists: out and the run builds the player’s train from the vehicle picked in the
menu. That is what probefahrt.ron does, and why its player_train is 0.
3. Events: triggers and actions
Section titled “3. Events: triggers and actions”The core of a scenario is its events: list. Each event has a unique name, one trigger
and a list of actions. It fires once, unless it says once: false. From
probefahrt.ron:
events: [ ( name: "welcome", trigger: Time(2.0), actions: [Message("Test run: proceed to the main signal at km 2.0.")], ), ( name: "arrived", trigger: TrainStopped(train: 0, edge: EdgeId(0), s: 1980.0, radius: 60.0), actions: [ Score(points: 20, reason: "Stopped at the signal"), Finish(success: true, reason: "Test run complete"), ], ),],The triggers the format knows:
| trigger | true when |
|---|---|
Time(seconds) |
the run has lasted that long |
TrainPast(train, edge, s) |
the head of the train has reached or passed the point |
TrainStopped(train, edge, s, radius) |
the train stands within radius metres of the point |
SpeedAbove(train, kmh) / SpeedBelow(train, kmh) |
its speed is above / below the threshold |
SignalStop(signal, stop) |
the signal shows stop (stop: true) or proceed (false) |
ForcedBrake(train) |
the train protection has intervened |
After(event, delay) |
delay seconds after the named event fired |
All([…]) / Any([…]) |
all / at least one of the nested triggers |
Never |
never on its own; a script fires it (step 5) |
And the actions:
| action | does |
|---|---|
Message("…") / Announcement("…") |
a message to the player / an announcement |
SetSwitch(node, position) |
throws a switch (Straight / Diverging) |
RequestRoute(RouteId(i)) / ReleaseRoute(RouteId(i)) |
sets / releases a route of the interlocking |
SetWeather(preset) |
moves the weather to a preset over five minutes, a front rather than a switch |
SetRail(Dry | Wet | Slippery) |
the rail condition alone, until the weather next changes |
Score(points, reason) |
adds or deducts points |
Finish(success, reason) |
ends the run |
Texts in messages and reasons are mod content, written in the language your mod ships. They do not go through the simulator’s translation.
On a line built from modules, a module: on the scenario or on a single event makes its
indices module-local (Modules and compositions).
4. Add a timetable for stop scoring
Section titled “4. Add a timetable for stop scoring”Without a timetable only the scenario’s own points count. With one, the scoring also counts position error and delay at every stop.
- Create
timetable/probefahrt.ronwith the train’s number, category and stops. - Use
kind: Scenario: the times are seconds from the start of the run, and the timetable runs once. - Reference it from the scenario with
timetable: Some("example:probefahrt").
( number: "Lt 91351", category: "Lt", kind: Scenario, stops: [ ( name: "Beispielstadt Bksig", edge: EdgeId(0), s: 1980.0, arrival: 150.0, departure: 210.0, platform: "1", ), ],)The other kind, Daily, reads the times as seconds since local midnight and wraps around
every 24 hours. That is the looping all-day timetable an AI train can follow indefinitely,
and it is anchored by the scenario’s start: clock.
5. Start and test the scenario
Section titled “5. Start and test the scenario”From the repository root:
cargo run -p app -- --scenario example:probefahrtUseful flags while you iterate:
| flag | does |
|---|---|
--line <mod>:<name> |
runs on another line or composition than the scenario names |
--time 22:30 |
moves the run’s start clock |
--date 2026-01-15 |
moves the run’s start date (and with it season and sun) |
--weather snow |
lets that preset move in over five minutes; with --screenshot it is placed at once |
A few things to check on a test run:
- Every
TrainStoppedandTrainPastpoint lies where you think it does: drive there and see whether the event fires. - An event that never fires usually addresses the wrong
train:, a point on another edge, or a radius that is too small. - Warnings about the scenario go to the log. See Troubleshooting.
6. A script for what a trigger cannot say
Section titled “6. A script for what a trigger cannot say”A trigger table has no memory. “The train has been standing for 60 seconds after it had already moved” cannot be written as a trigger. That is what a script is for, and the rule is: the script decides when, the RON says what.
probefahrt does it the simplest way. The RON declares an event that never fires by itself:
( name: "stalled", trigger: Never, actions: [ Announcement("Dispatcher: are you having trouble? Report your position."), Score(points: -5, reason: "Unscheduled stop"), ],),and names a script with script: Some("example:probefahrt"), which is
scripts/probefahrt.lua. That script
uses the older hook shape: on_frame(ctx) reads the speed from ctx and answers with
{ fire = { "stalled" } } once the train has stood long enough. It still runs, but new
scripts should use the director API below. In it the same thing is cr.fire("stalled").
7. The director: a scenario told as a story
Section titled “7. The director: a scenario told as a story”A scenario script is the director of the run. Through the cr API it reads the whole
world, sets the player tasks, puts trains on the line, gives AI drivers work, scores and ends
the run. rangierfahrt is told entirely this way: its RON says only what stands on the line,
and scripts/rangierfahrt.lua does
the rest.
- Name the script in the scenario:
script: Some("example:rangierfahrt")loadsscripts/rangierfahrt.lua. - Return a module table. Every handler on it is optional.
on_start()runs once at the first frame,on_tick(dt)at every 0.1 s mark of simulation time, and world events arrive ason_<event>(...). - Tell the story in a task that waits.
cr.start(fn)runsfnas a coroutine, and inside itcr.wait,cr.wait_untilandcr.wait_forwait without stopping anything else. - Put the steps on the HUD with
cr.task(id, text)and tick them off withcr.task_done(id)orcr.task_failed(id). - Score with
cr.score(points, reason)and end withcr.finish(success, reason).
The core of rangierfahrt.lua, shortened:
local M = {}
local ENGINE = 1 -- index in the scenario's consists: list
local function player() return cr.train(cr.player())end
local function story() cr.wait(2.0) cr.task("ausfahren", "Aus dem Abstellgleis 1 ausfahren") cr.task("kuppeln", "An den Lokzug bei km 3,8 kuppeln")
cr.wait_until(function() return not cr.at_yard(ENGINE, "Abstellgleis 1") end) cr.task_done("ausfahren")
cr.wait_until(function() local train = player() return train ~= nil and train.vehicles >= 4 end) cr.task_done("kuppeln") cr.score(10, "Lokzug gekuppelt") -- … wait until it stands at the goal, then: cr.finish(true, "Rangierfahrt beendet")end
function M.on_start() cr.start(story) cr.start(watch_speed) -- a second task: -5 points per excursion over 25 km/hend
-- A world event: the rake parted again before the goal.function M.on_uncoupled(train) if train == cr.player() and cr.objective("kuppeln") == "done" and not cr.finished() then cr.task_failed("bringen") cr.finish(false, "Lokzug unterwegs abgekuppelt") endend
return MRun it with:
cargo run -p app -- --scenario example:rangierfahrtThe player couples with Insert and uncouples with Home (Shunting).
Things worth knowing before you write your own:
- Every index starts at 0, as in the RON: trains, signals, routes, switches, services.
Only Lua’s own lists (
cr.trains(),cr.yards(),cr.services()) start at 1, so use the values in them, not their positions. - Reads see the world as it stood when the call began. Writes are commands that take
effect after the handler returns. A wrong argument (a road the line does not have) is an
error and switches the script off. A refusal by the world (nothing in reach to couple to)
comes back as a
refusedevent, and the script runs on. - Indices you write into the script are not moved on a composition. The RON’s indices
are. Add
cr.offset().edgesto an edge of your own, asrangierfahrt.luadoes for its goal. - Positions along the track:
cr.distance(train, target)gives the metres from the train’s front end to a road, another train or{ edge, s }.
AI trains and shunt jobs
Section titled “AI trains and shunt jobs”A script can bring traffic of its own. cr.spawn{…} takes the same consist as a
consists: entry, written as a table, and returns the new train’s index at once.
cr.drive(train, timetable) gives it an AI driver for a timetable, and cr.shunt(train, job)
one for a shunt job. A job is a table built from cr.moves, or a jobs/*.ron file named by
id, like jobs/lokzug_abstellen.ron:
( name: "Lokzug abstellen", moves: [ SetBack(Yard("Abstellgleis 1")), Uncouple(0), DrawUp(At(edge: EdgeId(0), s: 3700.0)), Stand, ],)cr.set_switch(1, "diverging") -- the points have to lie right firstcr.shunt(train, "example:lokzug_abstellen")The AI does not throw points for itself, so the script sets them (cr.set_switch) or sets a
route (cr.request_route). The move formats are in
Shunt jobs for the AI.
World events
Section titled “World events”Besides the handlers on the module, cr.on(event, fn) adds a listener and
cr.wait_for(event [, filter [, timeout]]) waits for one inside a task. Some of the events:
stopped / departed, coupled / uncoupled, entered / left a road, signal,
event (a RON event fired), refused and finished. The complete list with arguments, every
read and every command are in the reference: Scenario scripting.
The sandbox
Section titled “The sandbox”Each run gets a fresh Lua 5.4 state with table, string, math and coroutine, and no
io, os, require, filesystem or network. pairs visits keys in a fixed order and
math.random is seeded from the script’s name and the start of the run, so the same scenario
on the same day draws the same numbers. A script that raises an error or runs too long is
switched off, the HUD says so, and the run goes on without it. Keep your state in locals.
Details: The sandbox.
8. An operating day
Section titled “8. An operating day”The second way to use a line is an operating day in days/. Instead of one prepared run it
holds every service of a day, and the run picker offers the playable ones.
days/beispieltag.ron is complete.
- Create
days/<name>.ronwith aname,descriptionand thelineit belongs to. A day whoselinenames another line than the one picked is not offered. Leavelineout and it is offered everywhere. - Set the default
dateandutc_offset. The player can move the date in the run picker. - Set the default
weather:Dynamiclets the day make its own weather out of the date,Fixed(Rain)names one preset and holds it. The player can override this too. - Add the
services. Each has anumber,category,description, a headvehicle(Nonetakes what the player picked),cars, anoriginspawn point and itsstops. - Optionally say where the stock goes afterwards with
stable_at(a road of the line) andstable_way(SetBack, the default, orDrawUp). - Mark services the player should not be offered with
playable: false. The AI still runs them, so the line is not empty.
( number: "RB 30001", category: "RB", description: "Frühzug nach Beispielstadt", vehicle: Some("example:br101_afb"), cars: 3, origin: At(edge: EdgeId(0), s: 200.0, dir: 1), stops: [ (name: "Beispielbach", edge: EdgeId(0), s: 200.0, arrival: 22500.0, departure: 22500.0, platform: "1"), // 06:15 (name: "Beispielstadt", edge: EdgeId(0), s: 3800.0, arrival: 22980.0, departure: 23040.0, platform: "2"), // 06:23 ],),Service times are always seconds since local midnight, read as a Daily timetable that
wraps at 24 hours. A service that leaves at 23:50 and arrives at 00:12 is simply 85 800 and
720. The run starts two minutes before the player’s service departs. Every other service is
put on the line as its hour comes and driven by the AI, and its unit is reused by the next
service that needs the same stock.
A day may also declare consists: (stock standing there from the first minute, with or
without a timetable or a shunt: job) and a script:. That script is a director like a
scenario’s and also sees the services (cr.services(), working_start / working_end,
cr.offer_working). The full format: Operating days.
Start and test a day
Section titled “Start and test a day”The run picker offers the day under its line. Without the menu, --day and --service
take a service directly. --service is the index into the day’s services: list, starting
at 0. Without it, the first service is taken.
cargo run -p app -- --line example:beispielstrecke --day example:beispieltag --service 0--date 2026-01-15 moves the date of the service, so the same 06:15 departure becomes a
night run in winter. --weather and --time work as for a scenario. Drive a service to its
last stop and check that the next working is offered (F10 takes it), and that services
with stable_at end up on their road.
Multiplayer
Section titled “Multiplayer”Every scenario and every day also runs on a dedicated server, from the same file:
cargo run -p app -- --dedicated 27015 --scenario example:rangierfahrtKeep these points in mind while you write one:
- The server runs the director, never a client. A client receives what the world made of
the script’s commands and applies it. A script that changes the world only through
crworks in multiplayer with no extra effort. - Do not depend on the player. On a dedicated server nobody is “the” player, and
cr.player()returns the scenario’s train there. Several people may be on the line, so write checks against train indices, not against what one screen shows. - The consists are the server’s. Clients build the scenario’s trains, liveries and loads
from the server’s description. Their own menu and
--varianthave no say over them. - The operating day’s dispatching is a function of the clock. Server and clients put the same services on the line without sending anything about it. Only the driving is the server’s.
--timeand--weatherdo nothing on a server, so test a scenario’s sky through itsstart:andweather:fields, not through those flags.
Running and joining a server: Multiplayer.
Next steps
Section titled “Next steps”- Scenario scripting: the complete
crAPI, every world event, the sandbox and the multiplayer rules. - Modules, scenarios and operating days: compositions, module-local indices, consists, operating days and line hooks.
- Stabling roads and portals: the roads a scenario and a day stable and spawn trains on.
- Scenarios and timetable runs: what the player sees of all this.
- Publishing: pack the mod and share it.