Game and render threads
Two threads matter to a plugin. The render thread is where Wraith draws its overlay and your UI. The game thread is where the game’s own code runs. In most games they’re the same thread, but some engines, like Unity, run the game on a main thread and draw on another.
Draws and ticks
Section titled “Draws and ticks”threads.onDrawruns once a frame on the render thread, inside an ImGui frame, so it can draw. Windows fromui.addWindowdraw there too.threads.onTickruns once a tick on the game thread. It can’t draw, but it can call into the game, like an engine’s functions that only work on its main thread.
Draws are for UI, ticks are for game logic. By default they’re the same thread. Each tick runs on the render thread just before its draw, so you get a tick then a draw, every frame, and there’s nothing to set up.
import { Wraith } from "wraith";
let health = 0;
Wraith.threads().onTick(() => { // Read or change the game here health = readHealth();});
Wraith.ui().addWindow({ title: "Health", icon: "heart" }, () => { Wraith.imgui().TextUnformatted(`${health}`);});local Wraith = require("wraith").Wraith
local health = 0
Wraith.threads():onTick(function() -- Read or change the game here health = read_health()end)
Wraith.ui():addWindow({ title = "Health", icon = "heart" }, function() Wraith.imgui():TextUnformatted(tostring(health))end)Threads.Subscription? tickSub;Window? window;float health;
public override void Start(Context context){ tickSub = Threads.Instance.OnTick(() => { // Read or change the game here health = ReadHealth(); });
window = Ui.Instance.AddWindow(new Window.Options { Title = "Health", Icon = "heart" }, () => { ImGui.Instance.TextUnformatted($"{health}"); });}#include <atomic>#include <format>
#include "schema.hpp"
static std::atomic<float> health = 0;
// in startauto tick_sub = wraith::api().threads().onTick(sal::keep<Wraith::Threads::Tick>([] { // Read or change the game here if (auto* player = MyPlugin::Player::instance()) health = player->health;}));
auto window = wraith::api().ui().addWindow({.title = sal::String::of("Health"), .icon = sal::String::of("heart")}, sal::keep<Wraith::Window::Draw>([] { wraith::api().imgui().TextUnformatted(std::format("{}", health.load()).c_str());}));use std::sync::Mutex;
use salamander::Str;use schema::Player;use wraith::{ThreadsTick, WindowDraw, WindowOptions};
static HEALTH: Mutex<f32> = Mutex::new(0.0);
fn show_health() -> Option<()> { let tick_sub = wraith::api() .threads() .on_tick(ThreadsTick::keep(|| { // Read or change the game here if let Some(player) = unsafe { Player::instance().as_ref() } { *HEALTH.lock().unwrap() = player.health; } })) .ok()?;
let options = WindowOptions { title: Str::new("Health"), icon: Str::new("heart"), ..Default::default() }; let window = wraith::api().ui().add_window(options, WindowDraw::keep(|| { let text = format!("{}\0", *HEALTH.lock().unwrap()); wraith::api().imgui().text_unformatted(text.as_ptr().cast()); })); Some(())}sdk.threads.onTick is the SDK’s, and takes your context and a method.
pub fn start(self: *Plugin, ctx: *sdk.Context) !void { self.tick_sub = try sdk.threads.onTick(self, tick); self.window = ctx.wraith.ui().addWindow(.{ .title = "Health", .icon = "heart" }, .init(self, draw));}
fn tick(self: *Plugin) void { // Read or change the game here self.health = readHealth();}
fn draw(self: *Plugin) void { sdk.ui.text("{d}", .{self.health});}float read_health(void);static volatile float health;
static void tick(uintptr_t self) { (void)self; /* Read or change the game here */ health = read_health();}
static void draw(uintptr_t self) { (void)self; char text[32]; snprintf(text, sizeof text, "%g", health); Wraith_ImGui_TextUnformatted(Wraith_Api_imgui(w), text);}
static const Wraith_Threads_Tick_table tick_table = { SAL_TABLE(Wraith_Threads_Tick), .call = tick };static const Wraith_Window_Draw_table draw_table = { SAL_TABLE(Wraith_Window_Draw), .call = draw };
/* in start */Wraith_Threads_Subscription tick_sub;Wraith_Threads_onTick(Wraith_Api_threads(w), (Wraith_Threads_Tick){ 0, &tick_table }, &tick_sub);
Wraith_Window_Options options = { .title = SAL_STR("Health"), .icon = SAL_STR("heart") };Wraith_Window window = Wraith_Ui_addWindow(Wraith_Api_ui(w), options, (Wraith_Window_Draw){ 0, &draw_table });Both give a subscription, and its cancel() stops it. Everything you subscribe goes when your plugin does. threads.onGameThread() says whether you’re on the game thread right now.
sub.cancel() stops one.
sub:cancel() stops one.
sub.Cancel() stops one.
sub.cancel() stops one.
sub.cancel() stops one.
The SDK’s subscriptions stop with sub.unsubscribe().
Wraith_Threads_Subscription_cancel(sub) stops one.
Code that waits can move between threads. The rule is the same in every language: when you wait on Wraith, you carry on on the thread that made the call. Only hops move you.
threads.toGame()carries on on the game thread at its next tick, or right away if you’re there already.threads.toRender()carries on on the render thread, where drawing works.threads.toWorker()carries on on a worker, for slow or blocking work.threads.nextTick()carries on at the next tick, on the game thread.threads.nextDraw()carries on at the start of the next frame, on the render thread.threads.delay(ms)carries on after that many milliseconds, back on the thread that asked.
So after threads.nextDraw() you’re on the render thread, and after threads.toGame() everything you wait on carries on there till you hop again.
They give promises, so await them, in an async function or at the top of main.ts.
import { Wraith } from "wraith";
const threads = Wraith.threads();let shown = 0;
async function watch() { while (true) { await threads.toGame(); const health = readHealth(); await threads.toRender(); shown = health; await threads.nextDraw(); }}watch();They give promises. promise:await() waits for one, inside task.spawn.
local Wraith = require("wraith").Wraith
local threads = Wraith.threads()local shown = 0
task.spawn(function() while true do threads:toGame():await() local health = read_health() threads:toRender():await() shown = health threads:nextDraw():await() endend)They’re ToGameAsync, ToRenderAsync, ToWorkerAsync, NextTickAsync, NextDrawAsync and DelayAsync(ms), and give a Task to await. C# can’t await in unsafe code, so keep async methods out of unsafe classes.
float shown;
public override void Start(Context context) => _ = Watch();
async Task Watch(){ var threads = Threads.Instance; while (true) { await threads.ToGameAsync(); var health = ReadHealth(); await threads.ToRenderAsync(); shown = health; await threads.NextDrawAsync(); }}They give a sal::Future, so co_await them in a coroutine, any function that gives a sal::Future. 32-bit games built with MSVC have no coroutines, see Waiting.
#include <atomic>
float read_health();static std::atomic<float> shown;
static sal::Future<void> watch() { auto threads = wraith::api().threads(); for (;;) { co_await threads.toGame(); float health = read_health(); co_await threads.toRender(); shown = health; co_await threads.nextDraw(); }}
// in startwatch();They give a salamander::Future to .await, in an async block or function run by salamander::spawn.
use std::sync::Mutex;
use schema::Player;use wraith::ThreadsError;
static SHOWN: Mutex<f32> = Mutex::new(0.0);
async fn watch() -> Result<(), ThreadsError> { let threads = wraith::api().threads(); loop { threads.to_game().await?; let health = unsafe { Player::instance().as_ref() }.map_or(0.0, |p| p.health); threads.to_render().await?; *SHOWN.lock().unwrap() = health; threads.next_draw().await?; }}
fn start_watching() { let _ = salamander::spawn(watch());}Hops work in a task, started with ctx.spawn. They’re the SDK’s sdk.threads.toGame(io), toRender, toWorker, nextTick, nextDraw and delay. sdk.tasks.wait waits on anything else from Wraith, and carries on where you were.
try ctx.spawn(watch, .{ self, ctx.io });
fn watch(self: *Plugin, io: std.Io) !void { while (true) { try sdk.threads.toGame(io); const health = readHealth(); try sdk.threads.toRender(io); self.health = health; try sdk.threads.nextDraw(io); }}Tasks start on the render thread. Before stop, every task is cancelled, and their waits fail with error.Canceled so they can wind down.
C has no awaits. Each hop gives a sal_Promise, and its sal_Promise_then task runs once you’re there, like in Waiting.
float read_health(void);static volatile float shown;static float health;static sal_Promise hop;
static void on_game(uintptr_t self);static void on_render(uintptr_t self);static void on_frame(uintptr_t self);static const sal_Task_table on_game_table = { SAL_TABLE(sal_Task), .call = on_game };static const sal_Task_table on_render_table = { SAL_TABLE(sal_Task), .call = on_render };static const sal_Task_table on_frame_table = { SAL_TABLE(sal_Task), .call = on_frame };
static void next(sal_Promise p, const sal_Task_table *then) { hop = p; sal_Promise_then(hop, (sal_Task){ 0, then }, (sal_Queue){ 0, NULL });}
static void on_game(uintptr_t self) { (void)self; sal_Promise_release(hop); health = read_health(); next(Wraith_Threads_toRender(Wraith_Api_threads(w)), &on_render_table);}
static void on_render(uintptr_t self) { (void)self; sal_Promise_release(hop); shown = health; next(Wraith_Threads_nextDraw(Wraith_Api_threads(w)), &on_frame_table);}
static void on_frame(uintptr_t self) { (void)self; sal_Promise_release(hop); next(Wraith_Threads_toGame(Wraith_Api_threads(w)), &on_game_table);}
/* in start */next(Wraith_Threads_toGame(Wraith_Api_threads(w)), &on_game_table);The game thread is only there while frames run, or while a plugin holds ticks. Otherwise hops to it fail with NoFrames.
A JavaScript or Lua plugin only runs one thing at a time, on one thread at a time, so a hop just changes where its next part runs. While a script waits, other scripts and the game carry on.
When they’re different
Section titled “When they’re different”A plugin that knows the game’s own thread can take ticks over. It claims their lease with threads.claimTicks(), then calls threads.tick() from the game’s thread once a game frame, usually from a hook on the game’s update. The Unity plugin does this, so in Unity games onTick runs on Unity’s main thread. Other plugins’ onTick just runs there instead.
- Claim as your plugin starts. Ticks then wait for your first
tick(), so nothing runs on the wrong thread meanwhile. tick()does nothing unless you hold the lease. With nobody holding it, ticks go back to the render thread.- If the holder goes 30 seconds without ticking, Wraith logs it.
Drive ticks from a compiled language. A script’s hook is skipped while the script’s busy, and its ticks would be too.
Scripts shouldn’t drive ticks, see above. Leave it to a compiled plugin for the game.
Scripts shouldn’t drive ticks, see above. Leave it to a compiled plugin for the game.
The game’s update goes in a schema, like [Sig("48 89 5C 24 08")] void update();. Calling hook.Original() needs an unsafe class.
Lease? ticks;Hook? hook;
public override void Start(Context context){ // Here in Start, so nothing ticks on the render thread first ticks = Threads.Instance.ClaimTicks(null)!; hook = Hooks.Instance.Hook(Schema.Fns.Update, hook => { hook.Original()(); Threads.Instance.Tick(); });}The game’s update goes in a schema, like [Sig("48 89 5C 24 08")] void update();, and you hook it with hooks().detourNative. tick() is runTick() here.
#include "schema.hpp"
static Wraith::Hook hook;
static void on_update() { reinterpret_cast<MyPlugin::update_fn>(hook.original())(); wraith::api().threads().runTick();}
// in start// Here in start, so nothing ticks on the render thread firstauto ticks = wraith::api().threads().claimTicks({});if (auto at = wraith::api().schema().address(MyPlugin::update_name)) { if (auto made = wraith::api().hooks().detourNative(*at, reinterpret_cast<uintptr_t>(&on_update), {.disabled = true})) { hook = *made; hook.enable(); }}The game’s update goes in a schema, like [Sig("48 89 5C 24 08")] void update();, and you hook it with hooks().detour_native. tick() is run_tick() here.
use std::sync::atomic::{AtomicUsize, Ordering};
use wraith::{HookOptions, LeaseChanged};
static ORIGINAL: AtomicUsize = AtomicUsize::new(0);
unsafe extern "C" fn on_update() { let original: schema::UpdateFn = unsafe { std::mem::transmute(ORIGINAL.load(Ordering::Acquire)) }; unsafe { original() }; wraith::api().threads().run_tick();}
fn drive_ticks() -> Option<()> { let api = wraith::api(); // Here in start, so nothing ticks on the render thread first let ticks = api.threads().claim_ticks(LeaseChanged::default()).ok()?; let at = api.schema().address(schema::UPDATE_NAME).ok()?; let hook = api.hooks().detour_native(at, on_update as usize, HookOptions { disabled: true, ..Default::default() }).ok()?; ORIGINAL.store(hook.original(), Ordering::Release); hook.enable().ok()?; Some(())}The game’s update goes in a schema, like [Sig("48 89 5C 24 08")] void update();.
const schema = @import("schema").MyPlugin;const UpdateHook = sdk.hooks.Hook(schema, .update);
pub fn start(self: *Plugin, ctx: *sdk.Context) !void { _ = ctx; // Here in start, so nothing ticks on the render thread first self.ticks = try sdk.threads.claimTicks(.none); self.hook = try sdk.hooks.hookWith(schema, .update, update, self, .{ .enabled = true });}
fn update(self: *Plugin, hook: UpdateHook) void { hook.original()(); sdk.threads.tick();}The game’s update goes in a schema, like [Sig("48 89 5C 24 08")] void update();, and you hook it with Wraith_Hooks_detourNative. tick() is Wraith_Threads_runTick here.
#include "schema.h"
static Wraith_Hook hook;
static void on_update(void) { ((MyPlugin_update_fn)Wraith_Hook_original(hook))(); Wraith_Threads_runTick(Wraith_Api_threads(w));}
/* in start *//* Here in start, so nothing ticks on the render thread first */Wraith_Lease ticks;Wraith_Threads_claimTicks(Wraith_Api_threads(w), (Wraith_Lease_Changed){ 0 }, &ticks);
uintptr_t at = 0;Wraith_Schema_address(Wraith_Api_schema(w), SAL_STR(MyPlugin_update_name), &at);Wraith_Hook_Options options = { .disabled = true };if (at && Wraith_Hooks_detourNative(Wraith_Api_hooks(w), at, (uintptr_t)&on_update, options, &hook) == SAL_OK) Wraith_Hook_enable(hook);Never wait on either
Section titled “Never wait on either”Both threads hold up the game while your code runs, so never block on them. Hop to a worker with threads.toWorker() for slow stuff.
Wraith never waits on a script from either thread, and await doesn’t block. If a tick comes while the script’s busy drawing on the render thread, it skips that tick rather than holding up the game, and a frame that finds it busy with a tick skips too. When ticks and frames share a thread they take turns, so it never happens. When a game drives ticks from its own thread, keep each tick’s work short and expect the odd one to be skipped.
Wraith never waits on a script from either thread, and :await() doesn’t block. If a tick comes while the script’s busy drawing on the render thread, it skips that tick rather than holding up the game, and a frame that finds it busy with a tick skips too. When ticks and frames share a thread they take turns, so it never happens. When a game drives ticks from its own thread, keep each tick’s work short and expect the odd one to be skipped.
await doesn’t block, but .Wait() and .Result on Wraith’s tasks do, so don’t use them on either thread.
co_await doesn’t block. Don’t block either thread some other way, like waiting on a lock a worker holds.
.await doesn’t block, but future.wait() does, so don’t use it on either thread.
Waits that would block, like sdk.threads.onRender or sdk.tasks.wait outside a task, fail with error.OnRenderThread or error.OnGameThread there instead. In a task they park it rather than the thread.
Wraith’s calls don’t block, and a promise runs its task once it’s settled. Don’t block either thread some other way, like spinning till a promise settles.
Work of its own
Section titled “Work of its own”Native plugins can run work in the background, named so the workbench’s Jobs panel lists it under your plugin. Name kinds of work, like index files, not each one.
threads.run(name, job)runsjobonce on a worker. It’s fine to block there, like on a download.threads.startThread(name, main)gives a loop a thread of its own.maingets aThread: return oncethread.stopping()says so, andthread.sleep(ms)wakes early when you’re asked to stop.startThreadgives aRunningwhosestop()asks and waits. Wraith also stops your threads as your plugin unloads, afteronStopping, so you don’t have to.
Scripts run one thread at a time, so these fail with NotForScripts there. A script never needs to wait on a thread, since every slow call gives a promise: await it and Wraith carries on with other work meanwhile. For work that really needs a thread, use a native plugin.
Not for scripts. await slow calls instead, and hop with threads.toWorker() if you must.
Not for scripts. :await() slow calls instead, and hop with threads():toWorker() if you must.
Threads.Running? watcher;
public override void Start(Context context){ Threads.Instance.Run("index files", () => IndexFiles());
watcher = Threads.Instance.StartThread("watch saves", thread => { while (thread.Sleep(500)) CheckSaves(); });}// in startwraith::api().threads().run(sal::String::of("index files"), sal::keep<Wraith::Threads::Job>([] { index_files(); }));
auto watcher = wraith::api().threads().startThread(sal::String::of("watch saves"), sal::keep<Wraith::Threads::ThreadMain>([](Wraith::Threads::Thread thread) { while (thread.sleep(500)) check_saves();}));use salamander::Str;use wraith::{ThreadsJob, ThreadsThreadMain};
let threads = wraith::api().threads();threads.run(Str::new("index files"), ThreadsJob::keep(|| index_files())).ok()?;let watcher = threads .start_thread(Str::new("watch saves"), ThreadsThreadMain::keep(|thread| { while thread.sleep(500) { check_saves(); } })) .ok()?;wraith.io · Mods on the Hub · Get Wraith
Made with ♥ by Asgard
