upleb.uk

Public git repos — served from a NIP-34 GRASP relay at git.upleb.uk

summaryrefslogtreecommitdiff
path: root/docs/lua-modding.md
diff options
context:
space:
mode:
authorZack <zmasi21@gmail.com>2026-11-28 01:32:59 -0800
committerZack <zmasi21@gmail.com>2026-11-28 01:32:59 -0800
commit126058daed271ea3f8497541cd2e12fc31ab3067 (patch)
treed76dd55bbb3a316b025fdddda928b1f85b89c15b /docs/lua-modding.md
parent67ec1d35afaa9300e0e725dbbc06e7c851496841 (diff)
parent3ca0707ddec7fd868ecd6df924d751901102fd9c (diff)
Merge remote-tracking branch 'origin/main' into results/gpu-vega20-radv
Diffstat (limited to 'docs/lua-modding.md')
-rw-r--r--docs/lua-modding.md218
1 files changed, 218 insertions, 0 deletions
diff --git a/docs/lua-modding.md b/docs/lua-modding.md
new file mode 100644
index 000000000..3231797ed
--- /dev/null
+++ b/docs/lua-modding.md
@@ -0,0 +1,218 @@
1# Lua mods
2
3The D3D12 runtime (`d3d12/`, `leonida.exe`) runs Lua 5.4 mods. A mod is a folder in `mods\` with the same
4`mod.json` the mod manager (`tools/leonida_mods.py`, `Mods.bat`) already lists, and a script next to it:
5
6```
7mods\
8 my_mod\
9 mod.json {"name": "My mod", "enabled": true, "script": "main.lua"}
10 main.lua
11 helper.lua require("helper")
12```
13
14The scripts run in a sandbox on a thread of their own and can use what the runtime itself controls: frame, key and
15menu events, an overlay drawn over the picture, the live settings the F1 and F4 menus change, pages in the F4 trainer
16menu, and checked reads and writes of the title's memory with a byte-pattern scan. Single player only; nothing
17here touches anything online. The code is `d3d12/crates/leonida-lua`, `d3d12/crates/leonida-menu/src/overlay.rs` and
18`mods.rs`, and `d3d12/crates/leonida-gpu/src/host/trainer.rs` (where the overlay is drawn).
19
20Status: built and unit-tested (`cargo test -p leonida-lua --lib`, 35 tests, and the menu crate's); **not yet tried in
21the running title**. What that leaves open is listed at the end.
22
23## Trying it
24
251. Build with diagnostics for screenshots (`cargo build --profile diag -p leonida --features diagnostics`); the Lua
26 mods themselves are in every build.
272. Find the mods folder: `LEONIDA_MODS=<folder>` if set, else `mods` beside `leonida.exe` or in a folder above it
28 (so a build in `d3d12\target\...` finds the repository's `mods\`), else `mods` in the current folder. The log says
29 which (`Lua mods` line, target `lua`).
303. Set `"enabled": true` in `mods\example_lua\mod.json` (it ships disabled), start the title, and look at the lower
31 left corner: a frame-rate line. F4 opens the trainer menu; the last item, Mods, has the example's page.
32 After editing a script, F4, Mods, Reload Lua mods loads them all again (a fresh Lua state).
33
34`LEONIDA_LUA=0` turns it off completely: no thread, nothing per frame but one atomic load at present, no Mods page.
35
36## Events
37
38```lua
39leonida.on("frame", function(dt) end) -- once per presented frame (see below); dt in seconds
40leonida.on("key", function(key, down) end) -- "W", "F4", "Space", "Shift"...; true on press, false on release
41leonida.on("menu_open", function() end) -- the F4 menu was opened
42```
43
44Handlers run on the Lua thread, never on the present. If the Lua thread is slower than the frames, frames are
45coalesced: the handler runs once for all the presents since its last run, with `dt` the time since then. Key events
46come only while one of the runtime's windows is in front. Up to 64 handlers a mod. An unknown event name is an error.
47
48## Input
49
50```lua
51leonida.key_down("W") -- bool. Names: letters, digits, F1-F24, Enter Esc Tab Back Space Shift Ctrl Alt
52 -- LShift RShift LCtrl RCtrl LAlt RAlt Up Down Left Right Insert Delete Home End
53 -- PageUp PageDown Num0-Num9 NumAdd NumSub NumMul NumDiv NumDot CapsLock Pause
54 -- MouseLeft MouseRight MouseMiddle Semicolon Equals Comma Minus Period Slash
55 -- Tilde LBracket Backslash RBracket Quote. An unknown name is an error.
56local p = leonida.pad() -- the first connected pad: p.connected, p.a p.b p.x p.y p.lb p.rb p.back p.start
57 -- p.ls p.rs p.up p.down p.left p.right (booleans), p.lt p.rt (0 to 1),
58 -- p.lx p.ly p.rx p.ry (-1 to 1)
59leonida.hold_keys({"W", "Shift"}) -- the title sees these keys down, as LEONIDA_KEYS_FILE feeds them
60leonida.release_keys()
61```
62
63`hold_keys` sets the whole list (it replaces the mod's previous one); the title gets the union of what all mods hold.
64The stand-in pad the keyboard drives when no pad is connected sees them too. A mod that fails lets its keys go.
65
66## Overlay
67
68```lua
69leonida.text(x, y, "hello", {size = 20, color = "#FFE08A"}) -- (x, y) is the top left of the text
70leonida.rect(x, y, w, h, {0, 0, 0, 150})
71```
72
73Coordinates and sizes are pixels of a 1080-line picture and scale with the real picture's height. The list is cleared
74at the start of each pass: draw again each frame (in a `frame` handler) for what is to stay. Colours: a table
75`{r, g, b[, a]}` or `{r=, g=, b=, a=}` (0 to 255), a string `"#RRGGBB"` or `"#RRGGBBAA"`, or an integer (`0xRRGGBB`, or
76`0xRRGGBBAA` when it is above 24 bits); the default is white for text and translucent black for a rectangle. At most
771024 commands, 300 characters a text, text 6 to 200 px. The system's own fonts draw it (Segoe UI on Windows; the
78built-in dot font where there are none).
79
80The list is painted on the CPU into one picture the size of what is drawn (up to 4096 x 2304) and laid over the
81frame in one blended quad, where the F3 panel and the F4 menu are; an unchanged list is not painted again, so many
82small things cost little and a full-screen rectangle costs a fill of that size when it changes. A present pays one
83atomic load while nothing is drawn. The drawing is part of the picture frame generation sees; screenshots and saved
84frames do not have it.
85
86## Settings
87
88```lua
89leonida.get("fps_cap") -- nil when this run does not have it
90local ok, why = leonida.set("fps_cap", 60)
91for _, name in ipairs(leonida.settings) do ... end
92```
93
94| Name | Value | Same as |
95|---|---|---|
96| `fps_cap` | frames a second 1 to 1000, `0` for none, `"game"` for the title's own pace | the F1 menu's FRAME RATE CAP, `LEONIDA_FPS_CAP` |
97| `dlss_sharpness` | 0 to 1 (there when the title's upscale is DLSS) | DLSS SHARPNESS, `LEONIDA_DLSS_SHARPNESS` |
98| `panel` | true or false (diagnostics builds) | the F3 panel |
99| `menu_scale` | 0.6 to 1.6 | F4, Settings, Menu, Menu size |
100| `game_speed` | 0.1 to 2 (experimental, `docs/mod-menu.md`) | F4, World, Game speed |
101
102Any other name is refused: `set` returns `false` and why, `get` returns `nil`. Values outside the range are clamped.
103Nothing else of the runtime is reachable.
104
105## Trainer menu pages
106
107```lua
108local page = leonida.menu.page("My mod")
109local on = page:toggle("Enabled", true, function(value) end, "help text")
110local num = page:number("Amount", 2.5, {min = 0, max = 10, step = 0.5, decimals = 1, suffix = "x"}, function(value) end)
111page:action("Do it", function() end, "help text")
112on:get(); on:set(false) -- read or change what the menu shows
113```
114
115The pages of all mods are under F4, Mods (the last item of the main menu), after "Reload Lua mods". Callbacks run on
116the Lua thread when the player flips, moves or runs the item. At most 64 pages and 64 items a page (shared); labels
117are cut at 48 characters. After a reload, or when a mod fails and its pages go, the menu is on the Mods page again.
118
119## Memory
120
121Single-player modding of the title's own memory, through the runtime's checked copies (`host::read_into`,
122`safecopy`): an address that is unmapped, or a write to a protected page, gives `nil` or `false` and never faults.
123
124```lua
125local m = leonida.memory
126m.read_u8 / read_u16 / read_u32 / read_i32 / read_u64 / read_f32 / read_f64 (address) -- value or nil
127m.read_bytes(address [, n = 16]) -- Lua string or nil (n <= 1 MiB)
128m.write_u8 / write_u16 / write_u32 / write_i32 / write_u64 / write_f32 / write_f64 (address, value) -- true or false
129m.write_bytes(address, string) -- true or false
130m.base() -- the title's executable image: base, size (nothing before it is mapped)
131m.scan("48 8B ?? 05", {max = 100, start = address, size = n}) -- list of addresses, or nil and why
132```
133
134Little-endian, as the x86-64 title is; addresses are Lua integers (64-bit). Addresses below 64 KiB or above the user
135range are refused. Patterns are hex bytes with `??` (or `?`) for any byte, spaces optional, at least one real byte;
136`scan` covers the whole image by default, skips pages that are not mapped, never matches across a gap and returns at
137most `max` (default 100, ceiling 10,000) addresses in order. A scan of the 114 MB image reads it once in 1 MiB steps
138on the Lua thread, and the time it takes does not count against the mod's time budget.
139
140What it does not do: it does not know what the title keeps where. There is no table of the title's data here (the
141title's own script natives were not found, `docs/mod-menu.md`); a mod author finds addresses with `scan` and their
142own tools and takes the risk that a write corrupts the title. A write is checked to land on a page that can be
143written, not that it is sensible. Reads and writes race with the title's threads, as any trainer's do.
144
145## Misc
146
147```lua
148leonida.api_version -- 1. It changes only when something a mod may rely on does.
149leonida.version -- the runtime's version, a string
150leonida.log("a", 1, tbl) -- values joined by spaces, to the runtime's log (tracing target `lua`, the mod's name)
151print(...) -- the same, joined by tabs
152leonida.screenshot() -- the path the next frame is saved to, or nil and why (diagnostics builds)
153leonida.frame() -- presents counted so far (as the Lua thread last saw them)
154leonida.time() -- seconds since the mods started, a float
155leonida.read_file("data.txt") -- the contents, or nil and why
156leonida.write_file("sub/data.txt", s) -- true, or false and why
157require("helper") -- helper.lua (or helper/init.lua; dots are folders) of the mod's own folder, run once
158```
159
160Files: only the mod's own folder, plain relative paths (no `..`, drive letters, streams or reserved device names; a
161link that leads out is refused), reads up to 4 MiB, writes up to 1 MiB, never `mod.json` or a program (`.exe`, `.dll`,
162`.bat`, ...). There is no `io`.
163
164## The sandbox
165
166Each mod gets an environment of its own: copies of `assert error getmetatable ipairs next pairs pcall rawequal rawget
167rawlen rawset select setmetatable tonumber tostring type xpcall` and of the `coroutine`, `table`, `string`, `utf8`
168and `math` libraries, `os.time os.clock os.date os.difftime`, and `print`, `load`, `collectgarbage` and `require`
169made for it. One mod changing `string.rep` or `math.floor` changes nothing for another, and `getmetatable("")` gives
170a copy.
171
172Not there: `io`, `package` (so `package.loadlib` and any C module), `debug`, `dofile`, `loadfile`, `string.dump`,
173`os.execute`, `os.remove`, `os.rename`, `os.exit`, `os.getenv`, `os.tmpname`, `os.setlocale`. `load` takes text
174chunks only (a precompiled chunk can take the interpreter down), in the mod's environment unless one is given;
175`collectgarbage` does `"collect"` and `"count"`. There is no socket, HTTP or any other network function: the
176runtime offers none and the standard libraries that could reach one are not loaded.
177
178Limits: a call into a mod (loading it, a handler, a menu callback) may run for 200 ms (the load 2 s) of Lua; a loop
179that does not end stops with an error, also inside `pcall`, `xpcall` and `coroutine.resume`, which hand that error
180back instead of swallowing it. The whole Lua state may use 128 MiB. A coroutine can still yield through `pcall`.
181
182An error anywhere (the script's own, a handler, a menu callback, a bad argument, an exceeded limit) is logged with
183the mod's name and **disables that mod only**: its handlers, its menu pages and the keys it holds go, the other mods
184go on. A syntax error or a missing script is the same at load. A Rust panic in the runtime stops the Lua thread's work
185(the mods are dropped; three in all end the thread) and not the title.
186
187`mod.json`: `"script"` (a `.lua` path inside the folder), `"enabled"` (default true; the example ships `false`),
188`"name"` (shown in logs). A folder without `"script"` (an asset mod, `docs/modding.md`) is not a Lua mod and is left
189alone; a mod can have both. Load order is the folder names', sorted.
190
191## What is not here, and why
192
193- `leonida.teleport(x, y, z [, hold_seconds])` (true line, or nil and why) and `leonida.player_position()` (x, y, z) move
194 and read the player by memory, once the runtime knows where the player is (`docs/mod-menu.md`, "Teleport by memory").
195- God mode, wanted level, vehicles, weapons, weather, time of day: there is no `leonida.player` and no
196 `leonida.world` yet. With `LEONIDA_GAME_ACTIONS=1` the F4 menu does wanted level, time of day, weather and the
197 title's own cheats through the title's own code (`docs/mod-menu.md`, "Game actions"), and
198 `leonida.player_position()` is the ped's own position then; that is not offered to mods until it has run in the
199 title. A mod that wants the rest has the memory API and has to find the addresses itself.
200- Anything online, any file outside the mod's folder, any process or library: not offered, on purpose.
201- No keys, decryption or protection workarounds, and no game data in the repository: a mod holds its own script and
202 the addresses its author found, not pieces of the title.
203
204## Not tried yet
205
206Built, unit-tested and compiled into the runtime, but not run in the title: where the overlay lands on the real back
207buffer and how it looks with frame generation; that the `hold_keys` keys reach the title as `LEONIDA_KEYS_FILE`'s do;
208the checked write on the title's guarded memory; a scan of the real 114 MB image (the time it takes); the menu
209callbacks over the real F4 menu; Linux (the code is portable, but key and pad reading return nothing off Windows
210for now). `cargo test -p leonida-gpu --features diagnostics --lib host::trainer` was not run (it draws on a GPU);
211the draw path for the mods' overlay is not covered by it.
212
213## Tests
214
215`cargo test -p leonida-lua --lib` (the sandbox, event dispatch, a mod failing alone, endless loops, memory on a local
216buffer with unmapped, protected and out-of-range addresses, scans across chunks and holes, overlay, menu pages,
217settings, files, require, manifests, the API version) and `cargo test -p leonida-menu --lib` (the Mods page, the
218overlay painter, injected keys, `Menu::replace_pages`). No GPU, no title.