Skip to content

Latest commit

 

History

History
323 lines (256 loc) · 19.3 KB

API.md

File metadata and controls

323 lines (256 loc) · 19.3 KB

VI Scripting API

The Lua API a resource sees, in full. README.md covers installing the runtime, the console and the resource folders.

Each resource runs in its own Lua 5.4 state. Everything below is a global, and the thread functions are also in the Scripting table (Scripting.Wait, Scripting.CreateThread...).

Editor setup

The runtime writes Lua language server annotations for this whole API and every native to vi-scripting/types at each start. Point the editor at that folder for completion, signatures and type checks: in VS Code with the Lua extension, add to the workspace settings

{
    "Lua.workspace.library": ["<game folder>/vi-scripting/types"],
    "Lua.runtime.version": "Lua 5.4"
}

Threads

Wait(ms) Let the game run and come back in ms milliseconds; Wait(0) comes back at the next script tick
CreateThread(fn) Run fn as a thread from the next tick
CreateThreadNow(fn) Run fn as a thread at once, until its first Wait
SetTimeout(ms, fn) Run fn as a thread in ms milliseconds

Every entry into a resource (its files, threads, event handlers, commands, exports) is a coroutine, so Wait works anywhere. Script code runs on the game's script thread, once per script tick.

CreateThread(function()
    while true do
        Wait(0)
        -- once per tick
    end
end)

Events

AddEventHandler(name, fn) Call fn(...) whenever name is triggered; returns a handle {key, name}
RemoveEventHandler(handle) Remove a handler AddEventHandler returned
TriggerEvent(name, ...) Call every handler of name, in every resource

The runtime triggers onResourceStarting, onResourceStart and onResourceStop with the resource's name. Values that cross resources (event arguments, exports, commands) may be nil, booleans, numbers, strings, tables, vector3s and entities; functions and buffers do not cross.

Exports

exports('greet', function(name) return 'Hello, ' .. name end)   -- in resource hello
print(exports.hello:greet('you'))                               -- anywhere else

exports.resource.name(...) works too. An error in the export is raised at the caller's line.

Commands

RegisterCommand(name, fn) A console command: fn(source, args, raw), with source 0, args the words after the name and raw the whole line
ExecuteCommand(line) Run a console line at the next script tick

Names are case-insensitive and cannot replace the console's own commands. A command belongs to the resource that registered it last, and leaves with it.

Resources

GetCurrentResourceName() This resource's name
GetResourceState(name) 'started', 'starting', 'stopping', 'stopped' or 'missing'
LoadResourceFile(resource, path) The text of a file inside that resource's folder, or nil

Input and screen

IsKeyDown(key) Whether a key is held: a name, or a Windows virtual-key code. Always false while the console is open
RegisterKeyMapping(command, description, 'keyboard', key) A key that runs a command. A command named +name runs on press and -name on release
BlockGameKeyboard(on) The game gets no keyboard while any resource asks for it; a stopped resource lets go
Notify(text, seconds) A note in the corner of the screen, 4 seconds by default (0.5 to 30)

Key names: A..Z, 0..9, F1..F24, NUMPAD0..NUMPAD9, BACKSPACE, TAB, ENTER, SHIFT, CTRL, ALT, CAPSLOCK, ESCAPE, SPACE, PAGEUP, PAGEDOWN, END, HOME, LEFT, UP, RIGHT, DOWN, INSERT, DELETE, MULTIPLY, ADD, SUBTRACT, DECIMAL, DIVIDE. Letters follow the keyboard's layout: a script that wants the key left of S on QWERTY and AZERTY alike checks both A and Q.

Values

vector3

vector3(x, y, z) (or vec3) makes a vector; missing components are 0.

  • Fields x, y, z, readable and writable.
  • +, - between vectors; *, / with a number or component-wise with a vector; unary -.
  • #v and v:Length() are its length, v:Normalized() its direction.
  • == compares components; tostring(v) prints vector3(1, 2, 3).

Entities

Natives return entities as values of their own (the game's entity handles are 128 bits). The same entity is always the same value, so == works and entities can be table keys. e:IsNull() tells the null entity; e.lo and e.hi are its two halves. nil passes the null entity.

NativeBuffer

NativeBuffer(size) is zeroed memory (1 byte to 1 MiB) for natives that take a pointer.

buf.size, buf.address Its size in bytes and its address
buf:ReadInt(offset), ReadUInt, ReadInt64, ReadFloat, ReadBool, ReadVector3 Read at a byte offset
buf:WriteInt(offset, v), WriteInt64, WriteFloat Write at a byte offset

Reads and writes outside the buffer are Lua errors.

Helpers

joaat(text) The engine's string hash: case-insensitive, \ read as /
print(...) A line in the console, in the resource's channel. ^0..^9 change the color, ^0 resets

Natives

Every native is a global, by its name (GET_ENTITY_COORDS) or in PascalCase (GetEntityCoords). A part of the name that starts with a digit keeps its underscore (_PLAY_HUD_MESSAGE_03 is PlayHudMessage_03), and a native without a name is N_0x<hash>. The native table comes from ragetools/vi-natives; the console's natives <filter> searches it.

local ped = PlayerPedId()
local coords = GetEntityCoords(ped, false)
local visible, x, y = GetScreenCoordFromWorldCoord(coords)

Arguments and results

Before a call reaches the game, its arguments are checked against the table: their count and their types. A wrong call is a Lua error at the script's line and the game never sees it.

Table type From Lua To Lua
int, unsigned int, int64, Any integer, boolean, or a string (hashed with joaat) integer
Hash integer, or a string (hashed with joaat) integer
Cam, Blip, Player, Volume and the other handles integer integer
BOOL boolean or integer boolean
float number number
Entity, Ped, Vehicle, Object an entity a native returned, or nil entity
Vector3 vector3, {x, y, z}, or three numbers vector3
Vector2 vector3, {x, y}, or two numbers {x, y}
int*, float*, BOOL*, Hash*, Vector3*, Blip* nil (or a NativeBuffer) see below
Any* a NativeBuffer, an address, or nil see below
const char* a NativeBuffer, an address, or nil integer

Pointers. Where a native takes a pointer and the script passes nil, the native gets zeroed scratch memory. Once it returns, what it wrote there comes back after its own result, in the order of the parameters: an integer, number, boolean or vector3 for a typed pointer, the NativeBuffer itself for Any*. A pointer in the middle of the parameters still takes its place: _PARSEDDATA_TRY_GET_VECTOR(file, key, nil, 0). A script that passes its own NativeBuffer reads it itself.

Strings. Where the table says const char*, the game takes one of its script String objects, not text: a Lua string there is refused. Hashes are what most natives take instead, and a Lua string passes as its joaat hash wherever an integer or a Hash is expected.

InvokeNative and GetNativeInfo

InvokeNative(hash or name, ...) Call a native by its 64-bit hash or any of its names. A hash the table does not know is called with each argument by its Lua type and returns its first result cell as an integer
GetNativeInfo(name) nil, or {name, namespace, call, id, params, returns, bound, confidence}: call is its PascalCase name, params a list of {name, type}, bound whether this game build has its handler

Drawing over the game

The runtime draws over the game itself, with Dear ImGui, in the frame the game presents: no native runs for what a script draws, and nothing limits how much it draws but a cap of 250,000 calls per resource per tick. The game's own script natives have no lines, rectangles or text to draw.

Both APIs below work like the game's own drawing: what a resource draws shows for the ticks it is drawn in, so it draws from a thread that waits a tick at a time. What a resource drew is gone as soon as it stops or a thread of it fails.

CreateThread(function()
    while true do
        Wait(0)
        Draw.Text(20, 20, 'Hello', 0xFFFFFFFF)
    end
end)

Colors are an integer 0xAARRGGBB (0xFFFF0000 is opaque red; 0xFF0000 has no alpha and draws nothing) or an {r, g, b, a} table of 0 to 255 where a defaults to 255. Draw.Color(r, g, b, a) makes the integer.

Draw

Shapes and text in screen pixels, or at points of the world.

Draw.Line(x1, y1, x2, y2, color, thickness) A line; thickness 1 by default
Draw.Rect(x, y, w, h, color, thickness), Draw.RectFilled(x, y, w, h, color) A rectangle
Draw.Circle(x, y, radius, color, thickness), Draw.CircleFilled(x, y, radius, color) A circle
Draw.Text(x, y, text, color, size, flags) Text, at the font's size by default. Draw.TextFlags.Center centers it on the point, Draw.TextFlags.Outline outlines it in black; combine them with |
Draw.ScreenSize() The width and height of the last frame, in pixels
Draw.Line3D(from, to, color, thickness) A line between two points of the world
Draw.Text3D(pos, text, color, size) Text centered and outlined on a point of the world
Draw.Box3D(min, max, color, thickness) A box along the world's axes
Draw.BoundingBox(entity, color, thickness) The box of an entity's model, turned as the entity is
Draw.WorldToScreen(pos) The pixel a point of the world is drawn at, or nil behind the camera

Points of the world are vector3s or {x, y, z} tables. They are projected when the frame is presented, with the viewport the game's render thread drew that frame with, read in the game's memory: what a script places in the world stays on it while the camera moves. Lines that pass behind the camera are cut where they leave the view. Draw.WorldToScreen answers at the script's tick, with the viewport GET_SCREEN_COORD_FROM_WORLD_COORD uses. Draw.BoundingBox calls GET_ENTITY_MODEL, GET_MODEL_DIMENSIONS (once per model), GET_ENTITY_COORDS and GET_ENTITY_ROTATION, counted in the resource's natives.

On a game build whose viewports the runtime does not know, it falls back to the camera natives, read once per tick when a resource first draws in the world, and the drawing lags the camera by a frame.

The console's drawcheck command compares the runtime's projections with the game's own (GET_SCREEN_COORD_FROM_WORLD_COORD) for points in front of the camera, and prints the error in pixels of each. drawcheck render|game|tick picks where Draw takes its camera (render by default), and drawcheck vertical-degrees|horizontal-degrees|vertical-radians|horizontal-radians how the tick camera's field of view reads.

ImGui

Dear ImGui 1.89 for windows and widgets, under its own names in the ImGui table. A window shows while the resource calls ImGui.Begin for it at every tick.

local speed, god = 1.0, false

CreateThread(function()
    while true do
        Wait(0)
        local visible = ImGui.Begin('Player')
        if visible then
            speed = ImGui.SliderFloat('Speed', speed, 0.0, 10.0)
            local changed
            god, changed = ImGui.Checkbox('Invincible', god)
            if changed then
                SetEntityInvincible(PlayerPedId(), god)
            end
        end
        ImGui.End()
    end
end)

How it differs from Dear ImGui in C++. The calls of a tick are recorded and the frame the game presents draws them, so what the player does reaches the script at the next tick:

  • A widget that holds a value takes it and returns the new one first, then whether it changed: value, changed = ImGui.SliderInt('Hour', value, 0, 23).
  • Begin, item and window queries (IsItemHovered, GetWindowSize...) answer for the previous frame. Before their first frame, Begin, BeginChild, BeginTabBar, BeginTable, BeginMenuBar, BeginMainMenuBar and BeginListBox answer true, a TreeNode or CollapsingHeader true only with DefaultOpen, and popups, menus, combos and tab items false.
  • Every push has its pop and every scope its end in the same thread and the same tick, checked as the script runs: a mistake is a Lua error at its line, and a thread that waits or ends with a scope open loses the resource's drawing for that tick. Colors and style variables pushed before Begin, BeginChild or BeginTooltip may be popped inside them. SetNextWindowPos, SetNextWindowSize and SetNextWindowBgAlpha come right before the window they set, and widgets need a window.
  • Text is shown as it is, never read as a format. The format of a slider or an input holds one conversion of the widget's type.
  • Window names belong to their resource: two resources using the same name get two windows. Combo and ListBox indexes start at 1, table columns at 0.

Input. Script windows are a HUD that takes no input until ImGui.SetInteractive(true): while a resource asks it and draws something, the game loses the keyboard and the mouse (not the pad), Dear ImGui shows its cursor and the windows take clicks and keys. A resource that stops asking, stops drawing, stops or fails lets go. ImGui.IsInteractive() is what this resource asks. While the console is open, script windows always take input.

Windows Begin(name, open, flags) → visible, open (with open nil there is no close button), End() always; BeginChild(id, w, h, border, flags), EndChild() always; SetNextWindowPos(x, y, cond, pivotX, pivotY), SetNextWindowSize(w, h, cond), SetNextWindowBgAlpha(alpha)
Text Text, TextColored(color, text), TextWrapped, TextDisabled, LabelText(label, text), BulletText, Bullet()
Buttons Button(label, w, h), SmallButton(label), InvisibleButton(id, w, h), ArrowButton(id, ImGui.Dir.Left) → clicked
Values Checkbox(label, v); RadioButton(label, active) → clicked, or RadioButton(label, v, choice) → v, changed; Selectable(label) → clicked, or Selectable(label, selected, flags, w, h) → selected, clicked; ProgressBar(fraction, w, h, overlay)
Numbers SliderFloat, SliderInt(label, v, min, max, format, flags); DragFloat, DragInt(label, v, speed, min, max, format, flags); InputInt(label, v, step, stepFast, flags); InputFloat(label, v, step, stepFast, format, flags)
Text input InputText(label, text, flags), InputTextMultiline(label, text, w, h, flags), InputTextWithHint(label, hint, text, flags); with EnterReturnsTrue, changed is true on Enter only
Lists Combo(label, index, items, height), ListBox(label, index, items, height); BeginCombo(label, preview, flags) → EndCombo() when open; BeginListBox(label, w, h) → EndListBox() when open
Colors ColorEdit3, ColorEdit4(label, color, flags): the color comes back in the form it was given
Trees TreeNode(label, flags) → TreePop() when open; CollapsingHeader(label, flags); SetNextItemOpen(open, cond), SetNextItemWidth(w)
Tabs BeginTabBar(id, flags) → EndTabBar() when open; BeginTabItem(label, open, flags) → selected, open, then EndTabItem() when selected
Tables BeginTable(id, columns, flags, outerW, outerH, innerWidth) → EndTable() when open, 1 to 64 columns; TableSetupColumn(label, flags, widthOrWeight), TableSetupScrollFreeze(columns, rows) and TableHeadersRow() before the rows; TableNextRow(flags, minHeight), TableNextColumn(), TableSetColumnIndex(column)
Menus BeginMenuBar() → EndMenuBar(), in a window with WindowFlags.MenuBar; BeginMainMenuBar() → EndMainMenuBar(); BeginMenu(label, enabled) → EndMenu(); MenuItem(label, shortcut, selected, enabled) → clicked, or selected, clicked with a boolean selected
Popups OpenPopup(id, flags); BeginPopup(id, flags), BeginPopupModal(name, open, flags) → visible, open, BeginPopupContextItem(id, flags), BeginPopupContextWindow(id, flags), each → EndPopup() when open; CloseCurrentPopup(), IsPopupOpen(id)
Tooltips BeginTooltip() → EndTooltip() always; SetTooltip(text)
Layout Separator, SameLine(offset, spacing), NewLine, Spacing, Dummy(w, h), Indent(w), Unindent(w), BeginGroup/EndGroup, AlignTextToFramePadding, BeginDisabled(disabled)/EndDisabled, PushItemWidth(w)/PopItemWidth, PushTextWrapPos(x)/PopTextWrapPos, GetCursorPos, SetCursorPos(x, y), GetCursorScreenPos, GetContentRegionAvail
Style and IDs PushStyleColor(ImGui.Col.Text, color)/PopStyleColor(count); PushStyleVar(ImGui.StyleVar.Alpha, v), or (index, x, y) for the pairs (WindowPadding, FramePadding, ItemSpacing...), then PopStyleVar(count); PushID(id)/PopID()
Queries IsItemHovered(flags), IsItemActive, IsItemFocused, IsItemVisible, IsItemClicked(button), GetItemRectMin, GetItemRectMax, GetItemRectSize, IsWindowHovered(flags), IsWindowFocused(flags), GetWindowPos, GetWindowSize, CalcTextSize(text, wrapWidth), GetDisplaySize, GetTextLineHeight, GetFrameHeight
Plots PlotLines, PlotHistogram(label, values, overlay, scaleMin, scaleMax, w, h)
Draw lists GetForegroundDrawList(), GetBackgroundDrawList() and GetWindowDrawList() (in a window) give a list with AddLine(x1, y1, x2, y2, color, thickness), AddRect(x1, y1, x2, y2, color, rounding, thickness), AddRectFilled(x1, y1, x2, y2, color, rounding), AddCircle(x, y, r, color, segments, thickness), AddCircleFilled(x, y, r, color, segments), AddTriangle(x1, y1, x2, y2, x3, y3, color, thickness), AddTriangleFilled(x1, y1, x2, y2, x3, y3, color), AddText(x, y, color, text), AddPolyline({{x, y}, ...}, color, closed, thickness)

Flags are Dear ImGui's names without their prefix, combined with |: ImGui.WindowFlags.NoTitleBar | ImGui.WindowFlags.AlwaysAutoResize. The tables are WindowFlags, InputTextFlags, TreeNodeFlags, SelectableFlags, ComboFlags, TabBarFlags, TabItemFlags, TableFlags, TableColumnFlags, TableRowFlags, SliderFlags, ColorEditFlags, HoveredFlags, FocusedFlags, PopupFlags, Cond, Col, StyleVar, Dir and MouseButton. A flag a function does not take is an error.

What keeps the game running

  • A native that faults is caught: the call becomes a Lua error, the engine lock it held is released, and the console says where it faulted.
  • A native that would wait on a ped's update jobs from where scripts run (SET_ENTITY_COORDS on a ped) is refused for that tick: the next tick tries again.
  • A script that runs for more than a second without Wait is stopped with an error.
  • An error in a thread, an event handler or a command stops that thread only.
  • Events, exports and commands calling one another more than 16 deep are refused.
  • Each resource's Lua state is limited to 256 MiB. There is no io, os.exit, os.execute, dofile, loadfile, require or binary chunk loading.