Sharing between plugins
Plugins can lean on each other, like one that knows an engine and others that use it. List the ones you need in depends in your manifest so they load first.
There are three ways to share, from simplest:
- Schemas. A plugin that depends on another gets its schemas too, so it can use the same game types without copying them.
- Libraries. Script source that JS or Lua plugins
require, in the library’s own language. Compiled plugins can add them too. - Services. Objects other plugins call, in any language.
Schemas
Section titled “Schemas”Another plugin’s types are in its namespace, its id in PascalCase, so the freecam plugin’s are in Freecam. In your own .sal files they work by their short names, like your own do, as long as nothing closer has the same name. The full name, like Freecam.Rig, always works. See Namespaces.
Import the namespace from wraith, like import { Freecam } from "wraith", then they’re under it, like Freecam.Rig.at(address). Nothing’s a global.
Take the namespace from require("wraith"), like local Freecam = require("wraith").Freecam, then they’re under it, like Freecam.Rig.at(address). Nothing’s a global.
They’re C# in that namespace, like Freecam.Rig.
They’re in that namespace in your schema.hpp, like Freecam::Rig.
They’re in a module of your schema module, named for it in snake_case, like schema::freecam::Rig.
They’re in your schema import beside your own, like @import("schema").Freecam.Rig.
They’re in your schema.h with that namespace in front, like Freecam_Rig.
Libraries
Section titled “Libraries”A library is code other scripts load with require(name), and tweaks with @use name. libraries.add(name, language, source) adds one, and it’s there until your plugin goes. Libraries only work in their own language. Use a service to reach every language.
JS plugins load one with require(name) or import x from "name".
import { Wraith } from "wraith";
Wraith.libraries().add("hello", "js", "module.exports = (name) => `hi ${name}`;");A JS library is CommonJS style. Whatever it puts in module.exports is what require gives.
local Wraith = require("wraith").Wraith
Wraith.libraries():add("hello", "lua", "return function(name) return 'hi ' .. name end")Libraries.Instance.Add("freecam-math", "lua", "return { lerp = function(a, b, t) return a + (b - a) * t end }");wraith::api().libraries().add("freecam-math", "lua", "return { lerp = function(a, b, t) return a + (b - a) * t end }");wraith::api().libraries().add("freecam-math", "lua", include_str!("math.lua")).ok()?;try ctx.wraith.libraries().add("freecam-math", "lua", @embedFile("math.lua"));Wraith_Libraries_add(Wraith_Api_libraries(w), SAL_STR("freecam-math"), SAL_STR("lua"), SAL_STR("return { lerp = function(a, b, t) return a + (b - a) * t end }"));Services
Section titled “Services”A service is a trait in your schemas marked [Service]. It says what the other plugins can call. Say the freecam plugin has this:
[Service] trait Camera { void setSpeed(f32 speed); async Vec3 position(); void onMove(keep Mover mover);}
trait Mover { void moved(Vec3 pos); }Plugins that depend on yours get these types too, so both sides agree on them. Args and results are what the trait says, like numbers, strings, structs and other traits. A method marked async gives a promise.
Offering one
Section titled “Offering one”Your plugin gives an object for each [Service] trait in its own schemas. It fails to load if it marks a trait [Service] and doesn’t give one, so a typo shows up straight away.
Export an object with the trait’s name from main.ts:
import { Freecam } from "wraith";
let speed = 1;const movers: Freecam.Mover[] = [];
export const Camera: Freecam.Camera = { setSpeed(s) { speed = s; }, async position() { return { x: 1, y: 2, z: 3 }; }, onMove(mover) { if (mover) movers.push(mover); },};Return a table with the trait’s name from main.lua. Each method gets the object as self, then the args:
local speed = 1local movers = {}
local Camera = {}
function Camera:setSpeed(s) speed = send
function Camera:position() return { x = 1, y = 2, z = 3 }end
function Camera:onMove(mover) movers[#movers + 1] = moverend
return { Camera = Camera }Implement the trait’s interface, and give it from Service when it’s asked for by name:
sealed class MyCamera : ICamera{ float speed = 1; readonly List<Mover> movers = [];
public void SetSpeed(float speed) => this.speed = speed;
public Task<Vec3> PositionAsync(CancellationToken cancel) => Task.FromResult(new Vec3 { X = 1, Y = 2, Z = 3 });
public void OnMove(Mover? mover) { if (mover != null) movers.Add(mover); }}
sealed class Main : WraithPlugin{ readonly MyCamera camera = new();
public override void Start(Context context) { }
public override AnyObject Service(string trait) => trait == Camera.TraitName ? Camera.From(camera).Raw.AsObject() : default;}Give the trait’s type a class with its methods, with Freecam::Camera::of. An async one gives a sal::Future, so it can be a coroutine. Your plugin’s service gives it when it’s asked for, with wraith::offer.
#include <atomic>#include <mutex>#include <vector>
struct MyCamera { std::atomic<float> speed = 1; std::mutex lock; std::vector<Freecam::Mover> movers;
void setSpeed(float s) { speed = s; }
sal::Future<Wraith::Vec3> position() { co_return Wraith::Vec3{1, 2, 3}; }
void onMove(Freecam::Mover mover) { std::lock_guard held(lock); if (mover) movers.push_back(mover); }};
struct Plugin { MyCamera camera;
bool start() { return true; } void stop() {}
sal::Object service(std::string_view trait) { if (wraith::asks_for<Freecam::Camera>(trait)) return wraith::offer(Freecam::Camera::of(camera)); return {}; }};
WRAITH_PLUGIN(Plugin)Implement the trait’s Impl trait, like CameraImpl. Methods you leave out give zero, or Unsupported for a result. Your plugin’s service gives it when it’s asked for, with wraith::offer.
use std::sync::Mutex;
use salamander::Object;use schema::{Camera, CameraImpl, Mover};use wraith::Vec3;
struct MyCamera { speed: Mutex<f32>, movers: Mutex<Vec<Mover>>,}
impl CameraImpl for MyCamera { fn set_speed(&self, speed: f32) { *self.speed.lock().unwrap() = speed; }
fn position(&self) -> salamander::Future<Vec3, salamander::Code> { salamander::spawn(async { Ok(Vec3 { x: 1.0, y: 2.0, z: 3.0 }) }) }
fn on_move(&self, mover: Mover) { self.movers.lock().unwrap().push(mover); }}
static CAMERA: MyCamera = MyCamera { speed: Mutex::new(1.0), movers: Mutex::new(Vec::new()) };
struct Freecam;
impl wraith::Plugin for Freecam { fn start() -> Option<Self> { Some(Freecam) }
fn service(&self, trait_name: &str) -> Object { if wraith::asks_for::<Camera>(trait_name) { return wraith::offer(Camera::from_static(&CAMERA)); } Object::default() }}
wraith::plugin!(Freecam);List a function in services for each one. Its return type says which trait it’s for:
const schema = @import("schema").Freecam;const rt = sdk.salamander.rt;
const Camera = struct { speed: f32 = 1,
pub fn setSpeed(self: *Camera, speed: f32) void { self.speed = speed; } ...};
pub const Plugin = struct { camera: Camera = .{},
pub const services = .{camera};
pub fn camera(self: *Plugin) schema.Camera { return .init(&self.camera, rt.implement(schema.Camera, Camera)); } ...};Make a table of the trait’s methods, and give it from a service function passed to WRAITH_PLUGIN_WITH. Methods left out of the table, like position here, fail with Unsupported.
static sal_Host host;static sal_Owner *owner;static float speed = 1;static Freecam_Mover mover;
static void set_speed(uintptr_t self, float s) { (void)self; speed = s;}
static void on_move(uintptr_t self, Freecam_Mover m) { (void)self; mover = m;}
static const Freecam_Camera_table camera_table = { SAL_TABLE(Freecam_Camera), .setSpeed = set_speed, .onMove = on_move };
static sal_object service(sal_string trait) { if (!wraith_same(trait, sal_info_Freecam_Camera.name)) return wraith_no_service(trait); Freecam_Camera camera = sal_own_Freecam_Camera(host, (Freecam_Camera){ 0, &camera_table }, owner); return (sal_object){ camera.data, camera.table };}
static bool start(sal_Host h, wraith_Guest guest) { host = h; owner = guest.owner; w = wraith_root(guest); return true;}
static void stop(void) {}
WRAITH_PLUGIN_WITH(start, stop, service)Using one
Section titled “Using one”A plugin that depends on freecam gets its service as a function in its namespace, named after the trait with a small first letter, so Freecam.Camera is Freecam.camera(). The trait’s instance() gives the same. Scripts import Freecam from wraith like their own namespace.
import { Wraith, Freecam } from "wraith";
const camera = Freecam.camera();
camera.setSpeed(2);const pos = await camera.position();camera.onMove({ moved(pos) { Wraith.log().info(`${pos.x}`); } });Freecam.Camera.instance() is the same object.
local wraith = require("wraith")local Wraith, Freecam = wraith.Wraith, wraith.Freecam
local camera = Freecam.camera()
camera:setSpeed(2)task.spawn(function() local pos = camera:position():await()end)camera:onMove({ moved = function(self, pos) Wraith.log():info(tostring(pos.x)) end })Freecam.Camera.instance() is the same object.
Freecam.Camera.Instance is it. To hand over a trait, like a Mover, implement its interface too:
sealed class Printer : Freecam.IMover{ public void Moved(Vec3 pos) => Log.Instance.Info($"{pos.X}");}
var camera = Freecam.Camera.Instance;
camera.SetSpeed(2);var pos = await camera.PositionAsync();camera.OnMove(Freecam.Mover.From(new Printer()));context.Service<Freecam.Camera>("freecam") gives it too, or null if that plugin doesn’t give one.
wraith::service<Freecam::Camera>("freecam") gives it, by the plugin’s id, or one with no table if it doesn’t give one. Get it in start and keep it. To hand over a trait, like a Mover, make one with Freecam::Mover::of.
#include <format>
struct Printer { void moved(Wraith::Vec3 pos) { wraith::api().log().info(std::format("{}", pos.x)); }};
static Printer printer;static Freecam::Camera camera;
static sal::Future<void> use_camera() { camera.setSpeed(2); auto pos = co_await camera.position(); camera.onMove(Freecam::Mover::of(printer)); co_return {};}
// in startcamera = wraith::service<Freecam::Camera>("freecam");use_camera();wraith::service::<Camera>("freecam") gives it, by the plugin’s id, or one with no table if it doesn’t give one. Get it in start and keep it. To hand over a trait, like a Mover, implement its Impl trait too.
use schema::freecam::{Camera, Mover, MoverImpl};use wraith::Vec3;
struct Printer;
impl MoverImpl for Printer { fn moved(&self, pos: Vec3) { wraith::api().log().info(&format!("{}", pos.x)); }}
static PRINTER: Printer = Printer;
fn use_camera() { let camera = wraith::service::<Camera>("freecam"); camera.set_speed(2.0); camera.on_move(Mover::from_static(&PRINTER)); let _ = salamander::spawn(async move { let pos = camera.position().await?; Ok::<(), salamander::Code>(()) });}sdk.salamander.service gives it, by the plugin’s id, or null if it doesn’t give one.
const freecam = @import("schema").Freecam;
if (sdk.salamander.service(freecam.Camera, "freecam")) |camera| camera.setSpeed(2);wraith_service gives it in start, by the plugin’s id, or no table if it doesn’t give one. Keep it, since it only works there.
static Freecam_Camera camera;
static void moved(uintptr_t self, Wraith_Vec3 pos) { (void)self; char text[32]; int n = snprintf(text, sizeof text, "%g", pos.x); Wraith_Log_info(Wraith_Api_log(w), (sal_string){ text, n > 0 ? (uintptr_t)n : 0 });}
static const Freecam_Mover_table printer_table = { SAL_TABLE(Freecam_Mover), .moved = moved };
static bool start(sal_Host host, wraith_Guest guest) { w = wraith_root(guest); sal_object found = wraith_service(host, guest, SAL_STR("freecam"), &sal_info_Freecam_Camera); camera = (Freecam_Camera){ found.data, found.table }; Freecam_Camera_setSpeed(camera, 2); Freecam_Camera_onMove(camera, (Freecam_Mover){ 0, &printer_table }); return true;}
static void stop(void) {}
WRAITH_PLUGIN(start, stop)A plugin that depends on yours unloads before yours does, so its services never go away under it. Methods run on whatever thread called, so keep them quick.
Typing them
Section titled “Typing them”Your editor and build need the other plugin’s schemas. They’re found for each plugin you depend on in this order: the folder your devDepends names, your dev plugins, a folder by its name next to yours, the installed one, then the hub, which is downloaded into a cache. Only versions your depends allows count, except ones you’re working on. wraith sdk deps shows where each one came from.
For one you’re working on, point at it:
"depends": ["freecam"],"devDepends": { "freecam": "../freecam" }npm run types writes the typings, with each plugin you depend on in its own namespace.
wraith sdk lua types writes the types, and the VS Code extension runs it when your wraith.json changes.
wraith sdk cs types makes them C#, each in its own namespace, and your project runs it on every build.
wraith sdk cpp types makes them C++, each in its own namespace, and your build runs it whenever they change.
wraith sdk rust types makes them Rust, each in its own module, and your build.rs runs it whenever they change.
Your build finds them, and tells you if one’s missing. A package in build.zig.zon by the same name wins over the rest, for pinning one exactly.
wraith sdk c types makes them C, each with its own namespace in front, and your build runs it whenever they change.
Slots of your own
Section titled “Slots of your own”A service is something others call. A slot is the other way round: somewhere others add to, like viewers for a kind of file, each an object of a trait in your schemas. ui.defineSlot makes one, plugin.id to others, and its contributions() are what’s in it, in the order added:
// schemas/viewer.sal in the `sheets` plugintrait Viewer { string name(); void draw(u32 row);}import { Wraith } from "wraith";import { as } from "salamander";
const viewers = Wraith.ui().defineSlot({ id: "viewers", title: "Viewers", help: "Ways to show a row", trait: "Sheets.Viewer" });for (const v of viewers.contributions()) as("Sheets.Viewer", v).draw(7);local Wraith = require("wraith").Wraithlocal sal = require("salamander")
local viewers = Wraith.ui():defineSlot({ id = "viewers", title = "Viewers", help = "Ways to show a row", trait = "Sheets.Viewer" })for _, v in ipairs(viewers:contributions()) do sal.as("Sheets.Viewer", v):draw(7) endconst viewers = try ctx.wraith.ui().defineSlot(.{ .id = "viewers", .title = "Viewers", .help = "Ways to show a row", .trait = "Sheets.Viewer" });for (viewers.contributions()) |v| sdk.salamander.rt.host().adapt(schema.Viewer, v).draw(7);A plugin depending on yours adds an object of the trait with ui.contributeTo. It has to be that trait, or it fails with WrongTrait. A script names the trait its object implements with implement, since anything can go where any object does; native code passes one as any trait object:
import { Wraith } from "wraith";import { implement } from "salamander";
Wraith.ui().contributeTo("sheets.viewers", implement("Sheets.Viewer", { name() { return "Chart"; }, draw(row) { /* ImGui calls */ },}));local Wraith = require("wraith").Wraithlocal sal = require("salamander")
Wraith.ui():contributeTo("sheets.viewers", sal.implement("Sheets.Viewer", { name = function(self) return "Chart" end, draw = function(self, row) --[[ ImGui calls ]] end,}))static const Sheets_Viewer_table chart_table = { SAL_TABLE(Sheets_Viewer), .name = chart_name, .draw = chart_draw };
sal_object chart = { 0, &chart_table };Wraith_Contribution added;Wraith_Ui_contributeTo(Wraith_Api_ui(w), SAL_STR("sheets.viewers"), chart, &added);What a plugin adds goes with it. A slot goes with its plugin too, but what’s been added stays for it, so it’s all there again when that plugin reloads. ui.slots() lists plugins’ slots with Wraith’s own.
Wraith’s own slots take objects the same way, each of the trait its Slot.Info says: Wraith.PhotoPart for Photo mode’s, like a foldout in photo.inspector or a node in photo.scene, Wraith.SettingsSection for your page in settings, Wraith.HubButton for a tile on the overlay’s bar in hub, and Wraith.WorkbenchTab for workbench. Each trait’s describe says where it goes, like a part’s kind, so contributeTo is all it takes. In Zig, sdk.slots.addPhotoPart and addSettingsSection do it from a struct you keep and a function drawing it.
Services run on whatever thread called, so what they share needs guarding. To share a lock with other plugins, make one with sync.newLock() and hand it out through a service. Each plugin locks it through its own sync, and waiting never blocks, since sync.lock gives a promise.
import { Wraith } from "wraith";
const sync = Wraith.sync();
const lock = sync.newLock();await sync.lock(lock);try { // yours} finally { sync.unlock(lock);}local Wraith = require("wraith").Wraith
local sync = Wraith.sync()local lock = sync:newLock()
task.spawn(function() sync:lock(lock):await() -- yours sync:unlock(lock)end)var sync = Sync.Instance;
var shared = sync.NewLock()!;await sync.LockAsync(shared);try{ // yours}finally{ sync.Unlock(shared);}static sal::Future<void> guarded(Wraith::Sync::Lock lock) { auto sync = wraith::api().sync(); co_await sync.lock(lock); // yours sync.unlock(lock); co_return {};}
// in startauto shared = wraith::api().sync().newLock();guarded(shared);use wraith::{SyncError, SyncLock};
fn guarded(lock: SyncLock) { let _ = salamander::spawn(async move { let sync = wraith::api().sync(); sync.lock(lock).await?; // yours sync.unlock(lock); Ok::<(), SyncError>(()) });}
fn share() { let shared = wraith::api().sync().new_lock(); guarded(shared);}ctx.wraith.sync().newLock() makes one to share, and sdk.tasks.wait(sync.lock(lock)) waits for it in a task.
For your own threads, the SDK’s sdk.sync.Mutex is a Zig helper that works anywhere. In a task, waiting parks the task instead of holding up its thread, and its plugin stopping ends the wait with error.Canceled. Elsewhere, like in a hook, the thread waits.
lock: sdk.sync.Mutex = .{},
try self.lock.lock();defer self.lock.unlock();Wraith_Sync_lock gives a sal_Promise, settled once you have it, like in Waiting.
static Wraith_Sync_Lock shared;static sal_Promise locking;
static void locked(uintptr_t self) { (void)self; sal_Promise_release(locking); /* yours */ Wraith_Sync_unlock(Wraith_Api_sync(w), shared);}
static const sal_Task_table locked_table = { SAL_TABLE(sal_Task), .call = locked };
/* in start */shared = Wraith_Sync_newLock(Wraith_Api_sync(w));locking = Wraith_Sync_lock(Wraith_Api_sync(w), shared);sal_Promise_then(locking, (sal_Task){ 0, &locked_table }, (sal_Queue){ 0, NULL });When it’s let go of, whoever waited longest gets it next. What a plugin holds or waits for goes with it when it unloads, and the lock goes with the plugin that made it.
wraith.io · Mods on the Hub · Get Wraith
Made with ♥ by Asgard
