* feat(simulation): text format of simulation snapshots
A snapshot of a running simulation is a text file in the syntax of the scenery
files: entries of the form <type> <name> <key> <value> ... end<type>, the first
one a header which names the scenery. This is the text alone: entries, writer,
reader, the names of the things of a scenery, the plan of coupling changes and
the command line switches (--load-snapshot, --snapshot-at), in the core library
with unit tests. Nothing reads or writes a snapshot yet.
* feat(simulation): snapshot of time, weather, cells, switches and events (L1)
--snapshot-at <seconds> <file> writes a snapshot when the simulation has run
that long, --load-snapshot <file> puts one over the scenery once it has loaded,
before the first frame. This layer keeps the clock and the simulation timer,
the weather with the wind, the random engine, the memory cells, the switches,
the tracks an event can change and the ones made on the run, the traction
power sources, the event queue, the timers of the launchers and the lamps of
the signals.
While a snapshot is put back the event manager is suspended, so nothing in the
scenery reacts to it. Existing classes only get accessors for what was private
(the fraction of the second, launcher timers, the speed limit of a track, the
wind, the state of a power source, the event queue). Without the switches
nothing changes.
* feat(simulation): state of a vehicle's physics for snapshots (L3, core)
What TMoverParameters holds of a running vehicle, to and from an entry of a
snapshot: speed, load, controls, switches and relays, pantographs, doors,
engine and its cooling, the air of the pipes, of every reservoir of the brake
valve (with the flow it has yet to take in) and of the chambers of the driver's
valves, the vigilance device, the power circuits. In the core library, tested
on the real vehicle definitions: a
vehicle restored on a fresh one saves the same, and runs on next to the one it
was saved from.
The brake valves, the driver's valves and the vigilance device get accessors
for their private state (reservoirs(), latches(), pressures(), state()), a
reservoir one for the flow it has yet to take in; nothing else in the physics
changes. This comes before the vehicles of the scenery (L2), whose
speed and load are kept by it.
* feat(simulation): snapshot of vehicles and consists (L2)
Every vehicle is kept with the place of both its axles (track, distance,
direction, path of a switch, events still to set off), the way it faces, its
couplings with their flags, destination and, through its physics, speed and
load. Loaded, the vehicles are put straight where they were
(TTrackFollower::Place(), which trails no switch and fires no event), then
parted and joined until they are coupled as saved, whatever trainsets the
scenery made of them.
A vehicle of the snapshot the scenery does not have is skipped and reported,
one the snapshot does not know stays as the scenery made it, one which had left
the simulation is taken out again.
* feat(simulation): pantographs and passenger exchange in snapshots (L3)
What a vehicle keeps of its machinery beside its physics: the arms of the
pantographs as they stand under the wire, the time without voltage, the
passengers getting on and off, the lighting of the compartments, the headlight
toggles, the last force asked of the electrodynamic brake.
* feat(simulation): snapshot of the drivers and of the player's vehicle (L4)
A driver is kept with its orders and the one it is on, the name of its
timetable and its place in it, the consist it has, what it holds to (speeds of
signals and limits, the reason it stands, its timers and flags), its table of
what is ahead on the track with the point limits it has latched, its tables of
what the brake of the consist gives, and whether the AI drives. A driver who
had moved to another vehicle of its train is moved there.
A run loaded in ghost view (the test mode) is ready before its first frame, as
the run it goes on from was.
The snapshot also names the vehicle the player was in, which --load-snapshot
starts in unless -v says otherwise.
* feat(simulation): snapshotsave command, on [Ctrl]+[Shift]+[F9]
Writes a snapshot of the simulation to snapshots/<scenery>_<date>_<time>.snapshot
in the game folder. The command is the last one of the list, so the numbers of
the others stay.
* test: scenario cases which load a simulation snapshot and compare the run
A case with a "snapshot" section runs its scenery to a time, taking snapshots
on the way and at the end, then again from the first snapshot, and compares the
two ends: positions, speeds, pressures, couplings, cells, switches, drivers.
The snapshot saved right after loading has to be the one loaded.
tests/scenarios/snapshots.py reads the format and tells two snapshots apart.
The switches and the format are described in tests/scenarios/README.md.
* fix(simulation): a vehicle gone in the snapshot leaves its isolated sections
The scenery counts the axles of every vehicle in the isolated sections of
the tracks it puts it on. A vehicle the snapshot has as removed was only
taken off the list of its track, so its two axles stayed counted there and
the section never went free again: the next train on it went 4-6-4 axles
instead of 0-2-0, and its busy and free events never fired.
- A removed vehicle counts both axles out of the sections of their tracks,
is taken off the list of its track only if it's on it, and has no owner.
- The drivers a snapshot doesn't have are deleted as before, and no
vehicle keeps its owner pointing at one of them.
- The snapshot keeps the count of every isolated section and sets it after
the vehicles are placed: the vehicles a consist leaves behind as it goes
through a portal stay counted where they were, in the game too. A count
the placing gives other than the snapshot has is told in the log.
- A vehicle with two entries is placed once.
- TIsolated::axles() reads and sets the count.
- The harness compares the counts of the sections; a new case,
snapshot_td_portal_isolated, has a train leave through a portal from the
track of a section before the snapshot.
* fix(simulation): every value of a snapshot file is checked before it's used
A damaged or edited snapshot could put an index past a table, a count
which takes forever or a number out of the range of its type into the
simulation, and a file cut short was put back half way.
- Reading a value: a whole number has to be whole and fit its type (an
enum its underlying one), a float can't be past its largest value; what
doesn't fit is refused. Every refusal names the entry, the key and the
value, and goes to the log (errors.txt), up to 100 lines and a count.
- Ranges: coupler ends 0 or 1 and the flags of a coupling; couplings which
would close a ring of vehicles; the count of the points of a driver's
table and of its point limits (not past the keys of the entry), the
indices into the table (tablelast, semnext, semnextstop); the order
stack and its position, the timetable station, the driver's enums and
directions; the path, events and distance of an axle, facing and first
axle; the date and time; switch states, made track ends, crossing
segments, event siblings and times, launcher timers, the weather; the
load (amount, and a name which isn't a path); the whole numbers inside
number lists (flags of a table point, the stop of a coupler pair, the
track flags under a vehicle, the fuse count of a power source, the cab
of the vigilance device).
- The positions of the controllers are brought within the ranges of the
vehicle: master and secondary controller (set and actual), reverser,
cabs, light, compressor and wiper switches, brake handle, hand brake,
dimmer.
- A document with problems isn't loaded unless --load-snapshot-force says
so; a test run ends with the error code then. The header counts the
entries, so a file cut between two entries is found too. A file of a
newer version is a warning, not a problem.
- A snapshot is written to <file>.tmp and renamed over the file only when
the stream didn't fail.
- Unit tests of the reader on damaged input.
* feat(simulation): the pullee mode and the holding brake timer in snapshots
Of what #419 and #424 added to TMoverParameters, two are state: PulleeMode
(prepared for being hauled dead; the scenery sets it, PulleeModeSwitch()
can change it) and StopBrakeReleaseTimer (how long power has been asked
for, which lets the holding brake of a unit go after its delay). Both are
kept now, as "pulleemode" and "stopbrakereleasetimer". The others
(PressureSwitchBrakeCylinder, EmergencyBrakeMainOffPressure,
StopBrakeReleaseDelay) come from the vehicle definition and aren't.
* fix(simulation): the snapshot code without Sonar issues
No declaration shadows an enumerator, the variables used only by a
condition are declared in it, write_file takes its writer as a template,
the temporary file is a std::filesystem::path, the isolated sections are
looked up by a transparent hash, apply_couplings is split into helpers,
and the copies of the simulation's random engine are marked NOSONAR.
The test data has no http:// in it. No snapshot key or format changes.
* fix(brakes): TSt113 lists the control pressure once
TSt113::pressures() added CP on top of TH14K1::pressures(), which
already has it since #366 removed the CP of TSt113 that hid it. A
snapshot held the St113's control chamber twice. The second entry is
removed.
Tests: every driver's handle lists each pressure once, and the St113
pressures of an EN57 saved through a snapshot come back on a fresh one.
* fix(simulation): snapshots skip road traffic, refuse changed sceneries, keep misplaced vehicles apart
Cars of the road spawn points which a snapshot has on the road are no longer put back: the spawn point owns
them and the snapshot would leave them frozen on the track. They're counted in the log. The pooled cars keep
their AI drivers, which the snapshot used to delete.
A snapshot whose scenery fingerprint differs is refused unless --load-snapshot-force is given: tracks named
"#N" shift when a track is added. Each vehicle is checked against the x/y/z of its entry after placing. One
more than 1 m off, or one which can't be placed, goes back where the scenery put it, isn't coupled to the
placed vehicles, and keeps its scenery state and driver.
Couplings set from a snapshot keep to CompatibleCoupling, so no MU control between an electric and a diesel
loco (#520).
The snapshotsave key writes to snapshotsdir of eu07.ini (snapshots by default, ini only like screenshotsdir),
adds _2, _3... to a name that is taken, and shows where the file went.
* refactor(simulation): the snapshot reads and writes the private state of the vehicles through their own members
Since #552 the state of physics::Vehicle and of its parts is private, and since #531 the vehicle, the AI
and the cab live in other files under other names. The snapshot code is ported to that:
- the state of a vehicle's physics is saved and loaded by physics::Vehicle::SnapshotSave() and
SnapshotLoad() (physics/components/snapshot.cpp), with the tables of the variables in a nested
snapshot_members; capture_mover() and apply_mover() only hand it the entry. The parts with private
state (low voltage, line breaker, line contactors, protective relays, converter, air of the
pantographs, compressor, air supply) give a plain Snapshot of it and take it back
(TakeSnapshot(), RestoreSnapshot()); the rest goes through their queries and setters
- the keys, their order and the numbers in them are unchanged, so the snapshots written before load:
the fields that moved into the parts are mapped there (Mains to lineBreaker, PipePress to brakePipe,
BrakeCtrlPos to brakes, dizel_* to diesel, hydro_* to torqueConverter and retarder, eimv to
inductionMotor.state in the order of the old table, EngDmgFlag to equipmentFaults, ...)
- TDynamicObject: the machinery of a vehicle (sections, rail joints, the passenger exchange) is saved
by members of its own, as these are private now; MED_oldFED is the last ED demand of the consist's
brake blending (ConsistBrakeBlending::LastElectrodynamicDemand())
- TController: the driving flags are saved as the bits of iDrivigFlags they were, the running brake
test as the number of its stage, the uphill start and the braking shortfall from their structs;
StaticBrakeTest, which is gone, is written as 0 and not read
- the couplings take Coupling, CouplingSet and VehicleEnd; orders are DriverOrders
- the unit tests of the snapshot of a vehicle use the queries and the parts
* fix(simulation): carry the driver's coupling set in the snapshot as the bits of the set
iCoupler is a CouplingSet since 2098614f, which record::set()/get() can't take. It goes
through the converted values as a whole number, as the driving flags do: Bits() on save,
CouplingSet::FromBits() on load. The key and its values are the same as before.
* fix(simulation): a loaded snapshot counts the vehicles it left where they stand
apply_isolated() set every isolated section to the count of the snapshot, also where a
vehicle the load left at its scenery place (misplaced, forced load, road traffic not put
back) stands, or where the snapshot had it. The axles of those vehicles are now counted in
the sections they stand in and out of the ones the snapshot has them in, and the memory
cells of those sections say whether they are taken by that count.
An AI consist doesn't end on a vehicle the load left: the ends are then found along what is
coupled now, as CheckVehicles() finds them.
The player entry no longer writes the cab, which nothing read: the cab is the one the
vehicle has occupied (caboccupied of its entry).
* feat(simulation): the snapshot keeps a derailment and the brakes of a sleeping vehicle
A derailed vehicle came back on the rails. Its entry now keeps what derailed it (outcome,
cause, speed, the cause and side of the motion off the track, the acceleration, the
collision derailment) and the distance its criteria were last checked over; the
derailment the scenery and the test mode were told of (new_derailment()), so it isn't told
again; and with physics.derailment new the motion of the body off the track
(derail_motion::body::state()) with the timers of the vehicle off the track. The terrain
under it is gathered anew around it when it loads.
sleep_brakes, what a sleeping vehicle's brake force came from, is kept too.
All keys are new: an entry without them leaves the vehicle as the scenery made it, so files
written before still load. New scenario case snapshot_td_off_track.
* fix(simulation): the snapshot keeps the sanded start of an AI driver
#494 (in staging since the last runs of the snapshot cases) made a driver whose start
slipped keep sanding under power until the train is under way, and take the power down a
step at a time. Neither the flag nor the time of the last step down was kept, so on
linia61 the loaded run sanded one frame later than the run which went on and parted from
it 0.06 s after loading (suwnica2, 9 mm and 0.08 km/h at 600 s). Both are kept now
(sandedstart, sandedstarttime); an entry without them leaves the driver as it is.
* fix(simulation): the snapshot keeps a train running forked on a switch thrown under it
Staging's switch fork running (#496) gave the axles and the vehicles state of their own: the way of a
switch an axle ran onto (TTrackFollower::iPath, which it leaves the switch by after a throw), the ways it
remembers of the switches behind it (path_memory, read when the axle behind it comes onto one of them),
and per vehicle the switch its bogies or its coupled ends run forked on with whether that was told
(m_forkbogies, m_forkends). None of it was in a snapshot: a loaded train on a switch thrown under it
would have left it by the way it is set now and never derailed running forked.
- Place() sets the way of the switch from the path the axle is put on, as SetCurrentTrack() does, and
clears the facing entry the vehicle hasn't looked at (there is none between frames).
- A vehicle entry has the remembered ways of each axle, oldest first (axle0switch0, axle0way0...),
recorded again into an empty memory on load (path_memory::entries()), and the forked watches
(forkbogies, fork0, fork1 with their "told"). A name which isn't a switch is refused.
- New case snapshot_td_switch_thrown: the snapshot is taken while the second coach of
eu07_td_switch_thrown_facing_behind_derails runs forked and hasn't derailed yet; the loaded run derails
it the same way and the two files at 150 s are identical.
23 KiB
Script screens
Screens drawn by scripts, alongside the Python screens (pyscreen:, pydestinationsign:): Lua scripts, run by
LuaJIT, and WebAssembly modules, run by the WAMR interpreter (ref/wamr). A script gets the same input a Python
screen gets (the table in python_var_doc.md), returns an RGBA image and, in the cab, may send commands.
A Lua script is text, kept with the vehicles and the scripts/ folder like the Python screens, and changed with any
editor. A WebAssembly module is compiled from another language (Rust, C, Zig and the like).
Both run sandboxed: a script reaches only the functions of eu07 below, and reads files only from its own folder and
below. A Lua script gets no io, os, ffi, debug or require, and no precompiled code is loaded.
Unlike a Python screen, which refreshes after a time (python.updatetime, updatetime:), a script screen refreshes
every so many rendered frames, set in eu07.ini. A call into a script may run at most 200 million instructions
(Lua runs without the JIT compiler so that the limit holds). A script that fails, or runs over, is switched off, and
the reason goes to the log.
eu07.ini
| key | default | meaning |
|---|---|---|
luascreens.enabled |
1 | 0: no Lua screens; the vehicles show what they did before |
wasm.enabled |
1 | 0: no WebAssembly screens; the vehicles show what they did before |
screens.cabframes |
4 | a screen in the cab is refreshed every so many frames (1-1000) |
screens.externalframes |
30 | a screen outside the cab (destination sign) is refreshed every so many frames |
screens.gpupost |
1 | 0: led_post and resize of the Lua screens always run on the cpu, as they did before |
wasm.cabframes and wasm.externalframes, the first names of the last two, are read as well.
A screen may ask for a longer interval of its own (frames: below); the longer of the two counts. Screens sharing
an interval are spread over its frames, so they don't all refresh on the same one. A screen in the cab is refreshed
only while the player sits in that cab, a screen outside only while its vehicle is drawn.
.mmd
In the cab section, next to pyscreen::
luascreen: { ekran.lua target: screen01 frames: 6 parameters: id=1&mode=full }
wasmscreen: { ekran.wasm target: screen02 }
| key | meaning |
|---|---|
| (first token) | the script, relative to the vehicle folder when it has no path of its own |
target: |
the submodel the screen is drawn on (its texture is replaced); none for a screen that only sends commands |
frames: |
the screen's own refresh interval, used when longer than screens.cabframes |
parameters: |
extra key=value pairs, &-separated, added to the input |
A touch on the screen's submodel comes in the input as the list of points touches, as for the Python screens.
In internaldata:, next to pydestinationsign::
luadestinationsign: { scripts/led_111a20.lua parameters: kod_e=IC&kod_p=TLK&kod_o=R instance: name }
destinationsignbackground: make:scripts/led_111a20.lua?dummy=1
luadestinationsign: and wasmdestinationsign: take the keys of pydestinationsign: (instance:, parameters:,
background:) and frames:. The input is what a Python sign gets: the timetable ($timetable), _id1 (the
train), _id2 (the instance) and the parameters, read anew on every refresh, so the sign can follow the journey. The
vehicles of one train showing the same request share one screen and one texture. A static destination texture, when
there is one, still comes first.
A blank sign (background:, or the older destinationsignbackground:) named make:<script>.lua?<parameters> or
make:<script>.wasm?<parameters> is drawn once by that script, with the parameters as its input.
A vehicle may have pydestinationsign:, luadestinationsign: and wasmdestinationsign: side by side. The Lua sign is
used while the Lua screens are on, else the WebAssembly one while those are on, else the Python one; a release without
the script screens reads only the Python one. An unknown key in any of the blocks is skipped together with its value.
The image
width * height pixels of 4 bytes, R G B A, in sRGB, row by row from the top, as an image is drawn (PIL's
tobytes() of what a Python screen's _render returns). The game turns it bottom row first for the texture, as the
Python screens' abstractscreenrenderer does with FLIP_TOP_BOTTOM. Up to 4096 pixels on either side.
Lua scripts
A script returns a table with render(state), and optionally init(), called once after loading. Each screen has its
own Lua state, so what a script keeps in its variables stays between the refreshes of its screen.
local screen = {}
function screen.render(state)
local image = eu07.image(256, 128, { 32, 32, 32 })
image:fill_rect(0, 0, math.floor(state.velocity * 256 / 160), 128, { 0, 192, 0 })
return image -- or nil: nothing changed, the previous image stays
end
return screen
state is a table of the input: numbers, booleans and strings (UTF-8), and touches, a list of { x, y }. A
colour is a table { r, g, b }, each 0-255. Coordinates are in pixels, (0, 0) the top left corner.
| function | meaning |
|---|---|
eu07.image(width, height [, color]) |
a new image, black or in the colour, up to 4096 on either side |
eu07.font(path) |
a font of the Python LED screens: path .. ".png" and path .. ".txt", as led_util.load_font() reads them |
eu07.sprite(path) |
a sprite: path .. ".png", as led_util.load_spr() reads it |
eu07.include(path) |
runs another script and returns what it returns (local util = eu07.include("led_util.lua")) |
eu07.read_file(path) |
the contents of a file, or nil |
eu07.time() |
seconds of a steady clock shared by all screens, for animations (scrolling) that keep their pace whatever the refresh interval |
eu07.command(name, param1, param2) |
sends a command (the names of simulation::commandMap) to the vehicle of the cab; ignored outside the cab |
eu07.log(...), print(...) |
writes a line to the log |
Paths are relative to the script's folder and lead no higher. A character a font lacks is drawn with the font's first
glyph (led_util picks a random one).
| method | meaning |
|---|---|
image:width(), image:height() |
the size |
image:fill(color) |
fills the image |
image:set(x, y, color), image:get(x, y) |
a pixel; get returns r, g, b |
image:fill_rect(x, y, width, height, color) |
a rectangle, clipped |
image:draw_text(font, x, y, text, color [, spacing]) |
text from x rightwards, spacing columns between the characters (1); returns the x after it (led_util.draw_str) |
image:draw_text_right(...), image:draw_text_centered(...) |
the same, ending at x or centred on it (draw_strl, draw_strc) |
image:draw_sprite(sprite, x, y, color) |
the lit pixels of the sprite (draw_spr) |
image:draw_image(image, x, y) |
another image, clipped |
image:led_post([bloom]) |
led_util.render_post(): a new image, each pixel a 2x2 diode with a darker grid, glowing (bloom, on by default), in a 1 pixel black frame. see below for when it runs |
image:resize(width, height) |
a new image, scaled as Pillow's resize(..., Image.LANCZOS), with the same pixels. see below for when it runs |
image:copy() |
a new image, the same |
font:height(), font:text_width(text [, spacing]) |
the height, the width of a text (get_str_len) |
sprite:width(), sprite:height() |
the size |
The drawing, led_post and resize run natively in the game, so a script only says what goes where.
led_post and resize only note what is to be done; the image's size is known right away. They run when the image is
used:
- on the image
renderreturns, on the gpu, into the screen's texture. Only the screens that ask for them pay for them, and the texture gets the small image as drawn rather than the large one. The gpu gives the pixels of the cpu, give or take one step of brightness here and there, from rounding in single precision. - on the cpu, as soon as the script reads the image (
get), draws on it, or draws it on another image. - on the cpu, in the screens' worker, when the renderer can't do it on the gpu (the NVRHI renderer, OpenGL ES, a
shader that failed to load) or
screens.gpupostis 0. A shader that fails is logged once, and the cpu takes over.
Limits of a Lua script
Besides the 200 million instructions of a call, a Lua screen is held to what runs in C, where the count doesn't reach:
-
memory: a screen holds at most 128 MB: its Lua heap and the pixels of its images, fonts and sprites (4 bytes a pixel of an image, 1 of a font or a sprite). An object that would take the screen over is refused (
memory limit exceeded), and a screen found holding more stops with that error. Garbage doesn't count: the check collects it first, every thousand instructions and before the calls below. Between the checks the screen's heap goes through a counter of the game's, in front of LuaJIT's own allocator, which refuses a block that would take the screen over twice the limit as it is asked for (not enough memory, an error the script may catch). So what one instruction makes is held as well: a loop doubling a string (for i = 1, 11 do s = s .. s endon a 1 MBs) stops at the concatenation that would go over 256 MB, not at LuaJIT's own heap limit of about 2 GB; -
string.repmakes no string over 1 MB;string.format,table.concatandstring.gsub(with a string or a table to replace with) refuse a result that may be over the memory of a screen, counted from the lengths of what they are given; -
the pattern functions (
string.find,match,gmatch,gsub) backtrack, and some patterns take hours on a long subject (("a"):rep(1e6):find(".-b")). A call is refused (the pattern may take too long) when the steps it may take at worst are over 100 million, about a tenth of a second at worst: the length of the subject (plus one), times the length of the pattern, times the subject again for each repetition (*,+,-,%b, a back reference%1) but one followed by what always matches (nothing, as in a repetition that ends the pattern, or(.-)%s*$), times 2 for each?, and taken once rather than from every position for a pattern anchored with^(not ingmatch). A repetition of a character or a%class right before the final$(%s*$) counts the longest run of it in the subject rather than the whole subject. A plain search (findwithplain, or a pattern of no special characters) is the subject times the pattern. So a pattern ending in its only repetition ("[^\n]+","%d+") works on any subject, one more repetition ("(%w+)=(%w+)") on some 3 000 to 5 000 bytes, and each further one divides that a lot. The usual trim,s:match("^%s*(.-)%s*$"), costs the line times its longest run of spaces: a line of words, even a megabyte long, is fine, but a long run of spaces inside it is refused, since the trim really takes the square of that. A trim that stays linear on any string:local function trim(s) local first = s:find("%S") if not first then return "" end return s:sub(first, #s - s:reverse():find("%S") + 1) end -
xpcallis made ofpcall: the handler gets the error once it has left the function, and a coroutine may yield inside either. There is nonewproxy, so no finalizer (__gc) of the script's own: LuaJIT runs those without the instruction count; -
the game reads
renderandinitof the script's table in protected mode, so a metatable of the script's (__index) may provide them; one that fails or runs over switches the screen off.
WebAssembly modules
A module exports:
| export | meaning |
|---|---|
memory |
the linear memory |
screen_init() -> i32 |
optional; called once after loading. anything but 0 disables the screen |
screen_render() -> i32 |
called on every refresh. returns the address of the image, or 0 to keep the previous one |
screen_width() -> i32 |
the width of the image, asked after every screen_render that returned an image |
screen_height() -> i32 |
the height of the image |
Imports, module eu07 (keys and texts are a pointer and a length in bytes, in the module's memory):
| import | meaning |
|---|---|
value_type(key, key_len) -> i32 |
0 no such value, 1 float, 2 int, 3 bool, 4 string, 5 list of points |
get_float(key, key_len) -> f64 |
the value as a number (int and bool too); 0 when there is none |
get_int(key, key_len) -> i32 |
the value as an integer (a float is truncated) |
get_bool(key, key_len) -> i32 |
1 or 0 |
get_string(key, key_len, buffer, capacity) -> i32 |
copies the text, in UTF-8; returns its whole length, -1 when there is none |
get_vec2_count(key, key_len) -> i32 |
the number of points in a list (touches) |
get_vec2(key, key_len, index, out) -> i32 |
writes the point as two f32 at out; returns 1, or 0 when there is none |
command(name, name_len, param1, param2) |
sends a command (the names of simulation::commandMap) to the vehicle of the cab; ignored outside the cab |
log(text, text_len) |
writes a line to the log |
time() -> f64 |
seconds of a steady clock shared by all screens |
led_post(source, width, height, target, bloom) -> i32 |
led_util.render_post(), run natively: target takes (2 width + 2) x (2 height + 2); bloom not 0 for the glow. returns 1, or 0 for sizes over 4096 |
resize_lanczos(source, width, height, target, target_width, target_height) -> i32 |
Pillow's resize(..., Image.LANCZOS), run natively, giving the same pixels. returns 1, or 0 for sizes over 4096 |
file_read(path, path_len, buffer, capacity) -> i32 |
reads a file from the module's folder or below; returns the file's whole size, -1 when there is none or the path leads outside |
led_post and resize_lanczos take RGBA images in the module's memory and write alpha 255; the source and the
target may overlap. They are what makes LED boards fast enough: in the interpreter the same filters take some 30
times longer.
The module gets 64 KiB of stack and no heap from the host: it manages its own memory.
Building a module
With clang (any version with the wasm32 target), no C library:
// ekran.c
#include <stdint.h>
#define IMPORT(name) __attribute__((import_module("eu07"), import_name(name)))
IMPORT("get_float") double get_float(const char *key, int key_len);
IMPORT("command") void command(const char *name, int name_len, int param1, int param2);
#define WIDTH 256
#define HEIGHT 128
static uint32_t pixels[WIDTH * HEIGHT];
__attribute__((export_name("screen_width"))) int screen_width(void) { return WIDTH; }
__attribute__((export_name("screen_height"))) int screen_height(void) { return HEIGHT; }
__attribute__((export_name("screen_render"))) int screen_render(void) {
double const velocity = get_float("velocity", 8);
int const filled = (int)(velocity * WIDTH / 160.0);
for (int y = 0; y < HEIGHT; ++y)
for (int x = 0; x < WIDTH; ++x)
pixels[y * WIDTH + x] = x < filled ? 0xFF00C000u : 0xFF202020u; // A B G R, little-endian
return (int)(uintptr_t)pixels;
}
clang --target=wasm32 -O2 -nostdlib -Wl,--no-entry -o ekran.wasm ekran.c
Any language that compiles to WebAssembly works the same way (Rust wasm32-unknown-unknown, Zig, AssemblyScript),
as long as the module imports nothing but the eu07 functions above.
Scenery scripts
A scenery runs a Lua script with lua <file> in its .scn, while the scenery loads. The script registers events
and works with memcells, tracks and vehicles through the table eu07.events (event_create, event_dispatch,
memcell_update, writelog and the rest, see scripting/lua.cpp). It shares the sandbox of the Lua screens:
- the file is a path relative to the scenery folder (
scenery/), and stays inside it: no.., no drive, no leading/./and\both separate folders, on Linux too. It is text, of at most 16 MB; precompiled code is not loaded; - the script gets the base library,
table,string,mathandbit, and ofosonly the clock:os.time,os.clock,os.difftimeandos.date(with the C89 conversions only,%Y,%d,%Hand so on). It gets noio, the rest ofos,ffi,debug,jit,package,require,dofile,load,loadfileorloadstring; - a script that fails stops there, the error goes to the log with the file name and line, and the scenery goes on loading. An event handler that fails is logged with the name of the event, and the simulation goes on;
- the events, tracks, isolated circuits, memcells and vehicles the functions give (
event_find,track_find,memcell_find, the event and the vehicle an event handler gets...) are handles of their kind: equal for the same object, usable as keys of a table, and taken only where that kind goes. Another kind, or any other value, is an error (bad argument #1 to 'memcell_update' (eu07.memcell expected, got userdata));nil, which the find functions give for a missing object, is taken as no object, as before. An event run without a vehicle gives its handlernilfor the vehicle.
Instead of io, a scenery script reads and writes files through eu07, as the Lua screens read theirs:
| function | meaning |
|---|---|
eu07.read_file(path) |
the contents of a file of the scenery folder (scenery/), or nil: a regular file of at most 16 MB, the path as for lua <file> |
eu07.write_file(path, text) |
writes text (any bytes) to a file of the scenery's data folder, replacing what was there, and makes the folders of path; returns true, or nil and the reason |
eu07.read_data_file(path) |
the contents of a file of the scenery's data folder, or nil: what write_file wrote there |
The data folder is the scenery's own, in the player's folder of the game: %APPDATA%\MaSzyna\scenery_data\<scenery>\
on Windows, ~/.config/MaSzyna/scenery_data/<scenery>/ on Linux (~/Library/Application Support/MaSzyna/... on a
Mac), <scenery> being the .scn file without .scn (td.scn: scenery_data/td/). The game writes nowhere else
for a script, and never into its own folder; the log says where the folder is when the scenery loads its first
script. What is written there stays for the next run of the scenery, and the player may delete it.
A path to write to is relative, with / or \ between the folders, at most 8 folders deep and 200 bytes long, and
each name in it portable: no .., no ., no empty name, no drive, no : < > " | ? * or control
characters, no . or space at the end, and none of the names Windows keeps for its devices (con, nul, com1,
lpt1... with or without an extension). A file is at most 1 MB (1048576 bytes), and the data folder of a scenery holds at most 256
files and 16 MB together; a write over these limits is refused, and leaves the file as it was.
local saved = eu07.read_data_file("state.txt")
local runs = tonumber(saved or "0") + 1
local ok, reason = eu07.write_file("state.txt", tostring(runs))
if not ok then eu07.events.writelog("state not saved: " .. reason) end
A script written for the earlier full libraries stops at the first call to one of them (attempt to index global 'io' (a nil value) in the log). For a scenery you trust, eu07.ini can give the scripts all of LuaJIT's libraries
again:
| key | default | meaning |
|---|---|---|
lua.fulllibraries |
no | yes: the scenery scripts get all of LuaJIT's libraries (io, os, ffi, require...), and with them the files and programs of the computer. The Lua screens stay sandboxed |
Only eu07.ini turns it on: a config block of a scenery doesn't (the log says the key was ignored). Nor does it set
the other keys that would take a scenery out of its sandbox or reach the computer: execonexit, extcam.cmd,
extcam.rec, screenshotsdir, snapshotsdir, network.server, network.client, zmq.address, motiontelemetry, uart,
feedbackmode, feedbackport, nor does it switch on python.enabled, luascreens.enabled or wasm.enabled when
eu07.ini has them off. A scenery may still switch those three off, or lua.fulllibraries off, as it always could.