RynthSuite as of 2026-10-04 (internal c94715f): RynthOracle (based on Oracle of Dereth by Advis Eveldan) and RynthInventory, RynthAi patrol doorways and rooms, healing priority, strict monster priority, finish the wounded target, slayer weapons, arcs when clear, blasts like rings, learn unknown spells, looting fixes, release 2026.10.4.6

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Tom Bohar 2026-10-04 18:34:29 -04:00
commit 12ca25f911
426 changed files with 108239 additions and 7521 deletions

View file

@ -0,0 +1,19 @@
# RynthLua examples
Copy a file into `C:\Games\RynthSuite\RynthLua\Scripts\` (or make a folder `<name>\` and
save it there as `index.lua`), then `/lua start <name>` or press Start in the Lua panel.
Scripts that listen for events keep running until you stop them (`/lua stop <name>`).
- `world-demo.lua`: game.World and WorldObject: what's around you and in your packs, filters (class, name, function), the selection, and the object, tell, selection and chat events.
- `character-demo.lua`: game.Character: identity, vitals, skills, attributes, burden, inventory and equipment, enchantments, the spellbook, then every character event.
- `actions-demo.lua`: the action queue: using an item on yourself with `await`, a failure as a value, a callback, a spell cast with retries, and `RunAllOrdered`. It really acts: set `KIT_NAME` and `SPELL_ID` first.
- `library-demo.lua`: the modules: enums, `json`, `storage` (per script and per character), `filesystem`, `rynth.ai` and `rynthlua`.
- `hud-demo.lua`: a small script window (`require("views")`, `require("imgui")`): a counter button, a checkbox and a running time; `/hud` shows or hides it. `/lua hud bench <n>` opens a test window with n widgets for measurements.
- `xp-tracker.lua`: a tracker window: XP gained and per hour, kills, a health bar, and Reset with a tooltip; the first size set in `OnPreRender`.
- `hunt-settings.lua`: a settings form saved with `storage` (checkbox, slider, 0-based combo, text box) and a button that sets your combat mode; `/hunt` shows or hides it.
- `salvage-list.lua`: a list with buttons: your salvage, gathered in a spawned loop, a filter box, a scrolling region with `PushID` rows, and Use / Give buttons (Give waits for its result in a thread of its own). The buttons really act.
- `item-icons.lua`: an item list with icons: your pack items drawn with their AC icons (`views.Huds.GetObjectIconTexture`, `ImGui.ImageButton`, `ImGui.Image`), an `InputInt` for how many rows and a `DragFloat` for the icon size. Nothing acts on the game. Needs an engine from 2026-09-30 or later.
The window examples need RynthCore API v71 with ImGui on; see "Script windows" in the reference.
The API reference is `docs/RYNTHLUA.md` in RynthSuite; `Types/` has editor completion for VS Code.

View file

@ -0,0 +1,64 @@
-- actions-demo.lua: the action queue (game.Actions).
--
-- AC does one use / cast / move at a time. Every game.Actions call (and every WorldObject
-- action method: obj.Use(), obj.Give(npc), ...) queues an action and returns it at once;
-- await(action) waits until it has finished and returns it. Then:
-- action.Success true / false
-- action.Error "None", "TooBusy", "TimedOut", "InvalidSourceObject", ... (ActionError.X)
-- action.ErrorDetails what happened, in words
-- action.Result what it made (the new stack of a split, the appraised object, ...)
-- Options go in a table after the arguments: { Priority, TimeoutMilliseconds, MaxRetryCount,
-- SkipChecks, Name }; a callback function, too, gets the action when it finishes.
local KIT_NAME = "Healing Kit" -- something in your pack you can use on yourself
local SPELL_ID = 2 -- Strength Self I
local function report(a)
if a.Success then
print(("%s: done in %d ms"):format(a.Name, a.FinishedAt - a.StartedAt))
else
print(("%s failed: %s (%s)"):format(a.Name, a.Error, a.ErrorDetails))
end
end
-- 1. Use an item on yourself and wait for the server to finish it.
local kit = game.World.GetInventory(KIT_NAME)[1]
if kit then
report(await(kit.UseOn(game.CharacterId))) -- same as game.Actions.ObjectUseOn(kit, game.CharacterId)
else
print("No " .. KIT_NAME .. " in your pack; skipping the use.")
end
-- 2. Failures are values, not errors: check Success / Error.
local bad = await(game.Actions.ObjectUse(0x7FFFFFF0)) -- no such object
if bad.Error == ActionError.InvalidSourceObject then
print("As expected: " .. bad.ErrorDetails)
end
-- 3. A callback instead of await: the script carries on, the function runs when it's done.
local target = game.World.Selected or game.Character.Weenie
if target then
game.Actions.ObjectAppraise(target, function(a)
if a.Success then print("Appraised " .. a.Result.Name) else report(a) end
end)
end
-- 4. A cast. Fizzles and "You're too busy!" are retried (MaxRetryCount, 3 by default).
local mode = await(game.Actions.SetCombatMode("Magic"))
if mode.Success then
local cast = await(game.Actions.CastSpell(SPELL_ID, 0, { MaxRetryCount = 2, TimeoutMilliseconds = 8000 }))
report(cast)
if cast.CurrentRetryCount > 0 then print(" (took " .. (cast.CurrentRetryCount + 1) .. " tries)") end
else
report(mode)
end
await(game.Actions.SetCombatMode("NonCombat"))
-- 5. Several steps as one queue entry, in order; stops at the first failure.
local steps = await(game.Actions.RunAllOrdered({
game.Actions.Sleep(500),
game.Actions.InvokeChat("/e stretches."),
}))
report(steps)
print("Queue now: " .. tostring(game.ActionQueue))

View file

@ -0,0 +1,71 @@
-- character-demo.lua: a tour of game.Character (RynthLua v2).
-- Prints who you are, your vitals, a few skills and attributes, burden, what you carry and
-- wear, your enchantments, then watches the character events until you stop the script.
local C = game.Character
-- ── Who and what ────────────────────────────────────────────────────────────
print(tostring(C))
print(("%s, level %d, %s mode%s"):format(C.Name, C.Level, C.CombatModeName,
C.InPortalSpace and " (in portal space)" or ""))
print(("Vitae %.0f%% Busy: %s"):format(C.Vitae * 100, tostring(C.Busy)))
print(("XP %d (unassigned %d) Luminance %d / %d"):format(C.TotalExperience, C.UnassignedExperience,
C.AvailableLuminance, C.MaximumLuminance))
-- ── Vitals: shortcuts, by name, or by VitalId ───────────────────────────────
print(("Health %d/%d Stamina %d/%d Mana %d/%d"):format(C.Health, C.MaxHealth,
C.Stamina, C.MaxStamina, C.Mana, C.MaxMana))
print(tostring(C.Vitals))
local hp = C.Vitals.Health -- same object as C.Vitals[1] or C.Vital("Health")
print(("Health: %d of %d (unbuffed max %d)"):format(hp.Current, hp.Max, hp.Base))
-- ── Skills and attributes: a SkillId number or a name ───────────────────────
for _, name in ipairs({ "WarMagic", "LifeMagic", "MeleeDefense", "Healing" }) do
local sk = C.Skill(name)
print((" %-14s %4d (base %d) %s"):format(sk.Name, sk.Current, sk.Base, sk.TrainingName))
end
print("Trained skills:")
for id, sk in pairs(C.Skills) do -- every skill, keyed by SkillId
if sk.Training >= 2 then print((" %s %d"):format(sk.Name, sk.Current)) end
end
local str = C.Attribute("Strength")
print(("Strength %d (base %d), Self %d"):format(str.Current, str.Base, C.Attributes.Self.Current))
-- ── Burden ──────────────────────────────────────────────────────────────────
print(("Burden %d / %d (%.0f%%)"):format(C.BurdenUnits, C.MaxBurdenUnits, C.Burden))
-- ── Inventory and equipment (WorldObjects; filters: name, ObjectClass, function) ──
local inv = C.Inventory()
print(("Carrying %d items in %d side packs"):format(#inv, #C.Containers()))
for _, wo in ipairs(C.Equipment()) do print(" wearing/wielding: " .. tostring(wo.Name)) end
print("Pyreals: " .. C.InventoryCount("Pyreal"))
print("Mana stones: " .. #C.Inventory(function(wo) return (wo.Name or ""):find("Mana Stone") ~= nil end))
-- ── Enchantments and the spellbook ──────────────────────────────────────────
local enchantments = C.Enchantments()
print(("%d enchantments:"):format(#enchantments))
for _, e in ipairs(enchantments) do
local left = e.Permanent and "permanent" or (e.Remaining and ("%ds left"):format(math.floor(e.Remaining)) or "?")
print((" %s (%d): %s"):format(e.Name or "spell", e.SpellId, left))
end
print("Strength Self I active: " .. tostring(C.HasEnchantment(2)))
print(("Spellbook: %d spells; knows Strength Self I: %s"):format(C.SpellBook.Count, tostring(C.KnowsSpell(2))))
-- ── Events ──────────────────────────────────────────────────────────────────
C.OnVitalChanged.Add(function(e)
if e.Type == VitalId.Health and e.Value < e.OldValue then
print(("Ouch: health %d -> %d"):format(e.OldValue, e.Value))
end
end)
C.OnCombatModeChanged.Add(function(e) print(("Combat mode %s -> %s"):format(e.OldModeName, e.NewModeName)) end)
C.OnPortalSpaceEntered.Add(function() print("Entered portal space") end)
C.OnPortalSpaceExited.Add(function() print("Left portal space") end)
C.OnEnchantmentsChanged.Add(function(e)
print(("Enchantment %s%s: %s (%d)"):format(e.TypeName, e.Refreshed and " (refreshed)" or "",
e.Name or "spell", e.SpellId))
end)
C.OnDeath.Add(function(e) print("You died. " .. e.Text) end)
C.OnLevelChanged.Add(function(e) print(("Level %d -> %d!"):format(e.OldLevel, e.Level)) end)
C.OnVitaeChanged.Add(function(e) print(("Vitae %.0f%% -> %.0f%%"):format(e.OldVitae * 100, e.Vitae * 100)) end)
print("Watching character events; /lua stop character-demo to end.")

View file

@ -0,0 +1,56 @@
-- hud-demo.lua: a small window (script windows): a counter button, a checkbox and a
-- running time.
-- Needs RynthCore API v71 (engine) with ImGui on. Start it with /lua start hud-demo,
-- close the window with its X, bring it back with /hud (or the bar's Scripts button).
--
-- OnRender runs about 20 times a second on the plugin thread and records what to draw;
-- the engine draws it every frame. A click shows up as ImGui.Button returning true on the
-- next pass (one pass late), and ImGui.Checkbox returns (changed, newValue).
-- The full list of ImGui functions is in docs/RYNTHLUA.md ("Script windows"); see also
-- xp-tracker.lua, hunt-settings.lua and salvage-list.lua.
local views = require("views")
local ImGui = require("imgui")
if not views.Available then
print("Script windows aren't available here (engine older than API v71, or ImGui is off).")
end
local hud = views.Huds.CreateHud("Tracker")
hud.Title = "Tracker demo"
hud.Visible = true
local startedAt = clock()
local clicks = 0
local showTime = true
hud.OnRender.Add(function()
ImGui.Text("Hello, " .. (game.Character.Name or "?"))
ImGui.Separator()
if ImGui.Button("Count") then
clicks = clicks + 1
end
ImGui.SameLine()
ImGui.Text("clicked " .. clicks .. " time(s)")
local changed
changed, showTime = ImGui.Checkbox("Show running time", showTime)
if changed then print("Show running time: " .. tostring(showTime)) end
if showTime then
local s = math.floor((clock() - startedAt) / 1000)
ImGui.Text(("Running for %d:%02d"):format(math.floor(s / 60), s % 60))
end
if ImGui.SmallButton("Reset") then
clicks, startedAt = 0, clock()
end
end)
-- The player's X sets hud.Visible to false; /hud shows it again.
game.RegisterCommand("/hud", function()
hud.Visible = not hud.Visible
end)
print("Tracker hud open. /hud toggles it; /lua stop hud-demo closes it.")

View file

@ -0,0 +1,37 @@
-- hunt-settings.lua: a settings form (script windows) saved with storage: a checkbox, a
-- slider, a drop-down and a text box, plus a button that sets your combat mode.
-- Needs RynthCore API v71 (engine) with ImGui on. Start it with /lua start hunt-settings,
-- then type /hunt to show or hide the window.
--
-- The settings are only an example: nothing reads them but this form, and they are kept
-- in the script's storage (Data\hunt-settings\storage.json). The "Apply combat mode"
-- button really changes your combat mode.
--
-- Value widgets return two values, (changed, newValue): keep the new value, and save when
-- it changed. Combo's index is 0-based, as in ImGui.NET; the Lua list is 1-based.
-- The window isn't shown at start, so the player's last choice decides: it opens again
-- after a restart only if it was left open on this character.
local views, ImGui, storage = require("views"), require("imgui"), require("storage")
local s = storage.Get("settings", { enabled = true, range = 30, mode = 0, note = "" })
local modes = { "Melee", "Missile", "Magic" }
local function save() storage.Set("settings", s) end -- storage debounces the file write
local hud = views.Huds.CreateHud("Hunt Settings")
hud.OnRender.Add(function()
local ch
ch, s.enabled = ImGui.Checkbox("Enabled", s.enabled); if ch then save() end
ch, s.range = ImGui.SliderInt("Range (m)", s.range, 5, 60); if ch then save() end
ch, s.mode = ImGui.Combo("Mode", s.mode, modes); if ch then save() end -- 0-based, like UB
ch, s.note = ImGui.InputText("Note", s.note, 128); if ch then save() end
ImGui.Separator()
if ImGui.Button("Apply combat mode") then
game.Actions.SetCombatMode(modes[s.mode + 1])
end
end)
game.RegisterCommand("/hunt", function() hud.Visible = not hud.Visible end)
print("Hunt Settings ready: /hunt shows or hides the window.")

View file

@ -0,0 +1,63 @@
-- item-icons.lua: an item list with icons (script windows): your pack items with their
-- AC icons, an InputInt for how many rows to show and a DragFloat for the icon size.
-- Needs a RynthCore engine from 2026-09-30 or later (script windows "op level 2": icons
-- and number inputs) with ImGui on. Start it with /lua start item-icons.
--
-- Nothing here acts on the game: clicking an icon only picks that row.
--
-- views.Huds.GetObjectIconTexture(id) is the item as AC draws it (underlay, icon,
-- overlay). UB's way, views.Huds.GetIconTexture(iconId) + ImGui.Image(tex.TexturePtr, size),
-- works too. Until the engine has decoded a picture (a frame or two), or when it can't find
-- one, a dim square stands in: a missing icon is never an error.
local views, ImGui = require("views"), require("imgui")
local hud = views.Huds.CreateHud("Item Icons")
hud.Visible = true
hud.DefaultSize = Vector2.new(320, 360)
local rows, maxRows, iconSize, picked = {}, 25, 24, nil
spawn(function() -- gather the list once a second, not in every pass
while true do
local list = {}
for _, wo in ipairs(game.Character.Inventory()) do
list[#list + 1] = { id = wo.Id, name = wo.Name }
end
table.sort(list, function(a, b) return a.name < b.name end)
rows = list
sleep(1000)
end
end)
hud.OnRender.Add(function()
local changed
changed, maxRows = ImGui.InputInt("Rows", maxRows, 5, 25)
if changed then maxRows = math.max(1, math.min(maxRows, 200)) end
changed, iconSize = ImGui.DragFloat("Icon size", iconSize, 0.25, 16, 48, "%.0f px")
ImGui.Separator()
if ImGui.BeginChild("items", Vector2.new(0, -ImGui.GetFrameHeight() - 6), true) then
for i = 1, math.min(#rows, maxRows) do
local r = rows[i]
ImGui.PushID(r.id)
local tex = views.Huds.GetObjectIconTexture(r.id)
if ImGui.ImageButton("icon", tex, Vector2.new(iconSize, iconSize)) then picked = r end
ImGui.SetItemTooltip(r.name)
ImGui.SameLine()
ImGui.Text(r.name)
ImGui.PopID()
end
end
ImGui.EndChild()
if picked then
ImGui.Image(views.Huds.GetObjectIconTexture(picked.id), Vector2.new(16, 16))
ImGui.SameLine()
ImGui.Text("Picked: " .. picked.name)
else
ImGui.TextDisabled(#rows .. " items; click an icon to pick one")
end
end)
print("Item icons open. /lua stop item-icons closes it.")

View file

@ -0,0 +1,54 @@
-- library-demo.lua: the RynthLua library modules in one script.
-- Copy to C:\Games\RynthSuite\RynthLua\Scripts\library-demo.lua (or a folder
-- library-demo\index.lua) and start it with /lua start library-demo.
local json = require("json")
local storage = require("storage")
local ai = require("rynth.ai")
local fs = require("filesystem").GetData()
-- ── enums: globals, both ways ───────────────────────────────────────────────
print("SkillId.MeleeDefense = " .. SkillId.MeleeDefense) -- 6
print("ObjectClass[5] = " .. ObjectClass[5]) -- "Monster"
print("ChatType.Tell = " .. ChatType.Tell .. ", IntId.Value = " .. IntId.Value)
-- ── json ───────────────────────────────────────────────────────────────────
local snapshot = { script = game.ScriptName, when = os.time(), list = { 1, 2, 3 }, nested = { ok = true } }
local text = json.encode(snapshot)
print("json: " .. text)
local back = json.decode(text)
print("decoded list[3] = " .. back.list[3] .. ", nested.ok = " .. tostring(back.nested.ok))
local ok, err = pcall(json.encode, { fn = print })
print("encoding a function fails: " .. tostring(err))
-- ── storage: survives restarts, per script and per character ────────────────
local runs = storage.Get("runs", 0) + 1
storage.Set("runs", runs)
storage.Set("lastRun", snapshot)
print(("storage: this script has run %d time(s); keys: %s"):format(runs, table.concat(storage.Keys(), ", ")))
if game.State == "InGame" then
local mine = storage.Character.Get("runs", 0) + 1
storage.Character.Set("runs", mine)
print(("storage.Character: %d run(s) on this character"):format(mine))
end
-- ── filesystem: your own files in the data folder ───────────────────────────
fs.AppendText("log.txt", os.date("%Y-%m-%d %H:%M:%S") .. " run " .. runs .. "\n")
local lines = fs.ReadLines("log.txt")
print("filesystem: log.txt has " .. #lines .. " line(s), last: " .. lines[#lines])
local refused, why = fs.WriteText("../outside.txt", "nope")
print("writing outside the folder is refused: " .. tostring(why))
-- ── rynth.ai: only when RynthAi is loaded ───────────────────────────────────
if ai.Available then
print("RynthAi: macro " .. (ai.MacroRunning and "running" or "stopped"))
print("expression getcharvital_current[1] = " .. tostring(ai.Evaluate("getcharvital_current[1]")))
local portal, distance = ai.FindNearest("Portal", true)
if portal then print(("nearest portal: %s (%d) at %.1f m"):format(portal.Name or "?", portal.Id, distance)) end
else
print("RynthAi isn't loaded; rynth.ai calls would raise an error")
end
-- ── rynthlua: the plugin's own info ─────────────────────────────────────────
local info = require("rynthlua")
print(("RynthLua %s, data folder %s"):format(info.Version, info.DataFolder))

View file

@ -0,0 +1,57 @@
-- salvage-list.lua: a list with buttons (script windows): your salvage bags, a filter box,
-- and Use / Give buttons on each row.
-- Needs RynthCore API v71 (engine) with ImGui on. Start it with /lua start salvage-list.
--
-- The buttons really act: Use uses the bag, "Give to selected" gives it to whatever you
-- have selected.
--
-- The list is gathered in a spawned thread once a second, not in every pass: OnRender only
-- draws what it has. OnRender can't sleep or await, so the Give button starts a thread of
-- its own to wait for the result. PushID(r.id) gives each row's buttons their own IDs, so
-- every row can have a "Use" button.
local views, ImGui = require("views"), require("imgui")
local hud = views.Huds.CreateHud("Salvage")
hud.Visible = true
local rows, filter = {}, ""
spawn(function() -- refresh the data once a second, not in every pass
while true do
rows = {}
for _, wo in ipairs(game.Character.Inventory(ObjectClass.Salvage)) do
rows[#rows + 1] = { id = wo.Id, name = wo.Name, obj = wo }
end
sleep(1000)
end
end)
local function give(r)
local target = game.World.Selected
if not target then print("Select someone to give to first.") return end
spawn(function() -- OnRender can't await; a spawned thread can
local a = await(r.obj.Give(target))
if not a.Success then print("give failed: " .. a.Error .. " " .. (a.ErrorDetails or "")) end
end)
end
hud.OnRender.Add(function()
local _
_, filter = ImGui.InputText("Filter", filter, 64)
if ImGui.BeginChild("rows", Vector2.new(0, 0), true) then
for _, r in ipairs(rows) do
if filter == "" or r.name:lower():find(filter:lower(), 1, true) then
ImGui.PushID(r.id)
ImGui.Text(r.name)
ImGui.SameLine(220)
if ImGui.SmallButton("Use") then r.obj.Use() end
ImGui.SameLine()
if ImGui.SmallButton("Give to selected") then give(r) end
ImGui.PopID()
end
end
end
ImGui.EndChild()
end)
print("Salvage list open. /lua stop salvage-list closes it.")

View file

@ -0,0 +1,348 @@
-- RynthLua smoke test: exercises the v2 API in game and reports PASS / FAIL / INFO.
--
-- Run it somewhere safe (it switches combat mode and back, selects and appraises things;
-- it never uses, moves, drops or gives anything):
-- /lua run smoke-test
-- Results go to this script's console and to
-- C:\Games\RynthSuite\RynthLua\Data\smoke-test\results.txt
-- Afterwards it stays running for its chat command:
-- /smoketest hello -> answers "pong: hello" (tests script commands)
-- /smoketest stop -> stops the script via stop() (tests game.OnScriptEnd)
-- Run it again afterwards (or after /rc rl): the "persist" checks compare with the last run.
local json = require("json")
local storage = require("storage")
local fs = require("filesystem").GetData()
local ai = require("rynth.ai")
local info_m = require("rynthlua")
local C, W, A, Q = game.Character, game.World, game.Actions, game.ActionQueue
local lines, counts = {}, { PASS = 0, FAIL = 0, INFO = 0 }
local function out(kind, name, detail)
counts[kind] = counts[kind] + 1
local line = kind .. " " .. name
if detail ~= nil and detail ~= "" then line = line .. ": " .. tostring(detail) end
lines[#lines + 1] = line
print(line)
end
-- check(name, fn): fn returns ok [, detail]; an error is a FAIL with the message.
local function check(name, fn)
local ok, r, d = pcall(fn)
if not ok then out("FAIL", name, r)
elseif r then out("PASS", name, d)
else out("FAIL", name, d) end
end
-- note(name, fn): fn returns a value to report; never a failure unless it errors.
local function note(name, fn)
local ok, r = pcall(fn)
if ok then out("INFO", name, r) else out("FAIL", name, r) end
end
local function section(title)
lines[#lines + 1] = ""
lines[#lines + 1] = "== " .. title
print("== " .. title)
end
local function count(t) local n = 0; for _ in pairs(t or {}) do n = n + 1 end; return n end
local runStarted = os.time()
out("INFO", "started", os.date("%Y-%m-%d %H:%M:%S") .. " on " .. game.ServerName .. " as " .. C.Name)
-- ── Environment ───────────────────────────────────────────────────────────
section("Environment")
check("game.State is InGame", function() return game.State == "InGame", game.State end)
check("game.CharacterId", function() return game.CharacterId ~= 0, string.format("0x%08X", game.CharacterId) end)
check("game.ServerName", function() return game.ServerName ~= "", game.ServerName end)
check("game.ScriptName", function() return game.ScriptName == "smoke-test", game.ScriptName end)
check("rynthlua module", function() return info_m.Name == "RynthLua", tostring(info_m.Version) .. ", data " .. tostring(info_m.DataFolder) end)
check("clock() advances", function() local a = clock(); sleep(50); local b = clock(); return b - a >= 40, (b - a) .. " ms" end)
-- ── Persistence from the last run ─────────────────────────────────────────
section("Persistence (last run)")
local runs = storage.Get("runs", 0)
local lastStart, lastEnd = storage.Get("lastStart"), storage.Get("lastEnd")
if runs == 0 then
out("INFO", "first run", "run again after /smoketest stop (or /rc rl) to check persistence")
else
out("PASS", "storage kept the run count", "run #" .. (runs + 1))
check("game.OnScriptEnd saved on the last stop", function()
return lastEnd ~= nil and lastStart ~= nil and lastEnd >= lastStart,
"lastStart " .. tostring(lastStart) .. ", lastEnd " .. tostring(lastEnd)
end)
check("storage.Character kept its value", function()
local v = storage.Character.Get("seen")
return v == C.Name, tostring(v)
end)
end
storage.Set("runs", runs + 1)
storage.Set("lastStart", runStarted)
storage.Character.Set("seen", C.Name)
check("storage.Save()", function() return storage.Save() == true end)
game.OnScriptEnd.Add(function()
storage.Set("lastEnd", os.time())
storage.Save()
end)
-- ── Enums, json ───────────────────────────────────────────────────────────
section("Enums and json")
check("SkillId both ways", function() return SkillId.WarMagic == 34 and SkillId[34] == "WarMagic" end)
check("SkillId any case", function() return SkillId.warmagic == 34 end)
check("ObjectClass.Portal", function() return ObjectClass.Portal == 14 and ObjectClass[14] == "Portal" end)
check("CombatMode.Magic", function() return CombatMode.Magic == 8 end)
check("IntId.StackSize", function() return IntId.StackSize == 12 end)
check("ActionError.TooBusy", function() return ActionError.TooBusy == "TooBusy" end)
check("require('enums') == globals", function() return require("enums").VitalId.Mana == VitalId.Mana end)
check("json round trip", function()
local t = json.decode(json.encode({ a = 1, b = { 1, 2, 3 }, c = "x", d = true }))
return t.a == 1 and #t.b == 3 and t.c == "x" and t.d == true
end)
check("json empty table is []", function() return json.encode({}) == "[]", json.encode({}) end)
check("global json is RynthLua's", function() return type(json.encode) == "function" and _G.json.encode ~= nil end)
check("json error on a function", function() return not pcall(json.encode, { f = print }) end)
-- ── Character ─────────────────────────────────────────────────────────────
section("game.Character")
check("Name / Level", function() return C.Name ~= "" and C.Level > 0, C.Name .. ", level " .. C.Level end)
check("Id matches game.CharacterId", function() return C.Id == game.CharacterId end)
check("Weenie is you", function() local w = C.Weenie; return w ~= nil and w.Id == C.Id, tostring(w) end)
check("Health within Max", function() return C.Health > 0 and C.Health <= C.MaxHealth, C.Health .. "/" .. C.MaxHealth end)
check("Stamina / Mana", function() return C.MaxStamina > 0 and C.MaxMana >= 0, C.Stamina .. "/" .. C.MaxStamina .. ", " .. C.Mana .. "/" .. C.MaxMana end)
check("Vitals.Health matches", function() local v = C.Vitals.Health; return v.Current == C.Health and v.Max == C.MaxHealth, "base " .. tostring(v.Base) end)
check("Vitals[VitalId.Mana]", function() return C.Vitals[VitalId.Mana].Max == C.MaxMana end)
check("Vital('stamina')", function() return C.Vital("stamina").Max == C.MaxStamina end)
check("Skills has entries", function() local n = count(C.Skills); return n >= 30, n .. " skills" end)
check("Skill('war magic')", function()
local s = C.Skill("war magic")
return s.Id == 34 and type(s.Training) == "number" and type(s.TrainingName) == "string",
s.Name .. " " .. s.Current .. " (base " .. s.Base .. ", " .. s.TrainingName .. ")"
end)
check("Skill trained flag", function()
local s = C.Skills[SkillId.MeleeDefense]
return s.IsTrained == (s.Training >= 2), "Melee Defense " .. s.Current .. " " .. s.TrainingName
end)
check("Attributes", function()
local a = C.Attributes.Strength
return a.Current > 0 and C.Attribute(AttributeId.Self).Current > 0, "Str " .. a.Current .. " (base " .. a.Base .. ")"
end)
check("CombatMode is a number", function() return type(C.CombatMode) == "number" and C.CombatModeName ~= "", C.CombatModeName end)
check("Burden", function() return C.MaxBurdenUnits > 0, C.BurdenUnits .. "/" .. C.MaxBurdenUnits .. " (" .. string.format("%.0f", C.Burden) .. "%)" end)
note("Vitae", function() return C.Vitae end)
note("Busy / InPortalSpace", function() return tostring(C.Busy) .. " / " .. tostring(C.InPortalSpace) end)
note("Experience", function() return "total " .. C.TotalExperience .. ", unassigned " .. C.UnassignedExperience end)
check("SpellBook loads", function()
local ok = waitfor(function() return C.SpellBook.Count > 0 end, 6000)
return ok, C.SpellBook.Count .. " spells"
end)
check("KnowsSpell(first known)", function()
local ids = C.SpellBook.KnownSpellIds()
if #ids == 0 then return false, "spellbook empty" end
return C.KnowsSpell(ids[1]) and not C.KnowsSpell(65000), "spell " .. ids[1] .. " (" .. tostring(C.SpellBook.Name(ids[1])) .. ")"
end)
check("Enchantments()", function()
local e = C.Enchantments()
local sample = e[1] and (tostring(e[1].Name or e[1].SpellId) .. ", " .. tostring(e[1].Remaining) .. " s left") or "none active"
return type(e) == "table", #e .. " active; " .. sample
end)
local inv = {}
check("Inventory()", function() inv = C.Inventory(); return #inv > 0, #inv .. " items" end)
local equip = {}
check("Equipment()", function() equip = C.Equipment(); return #equip > 0, #equip .. " worn/wielded" end)
check("Equipment is inside Inventory", function()
local ids = {}
for _, wo in ipairs(inv) do ids[wo.Id] = true end
for _, wo in ipairs(equip) do if not ids[wo.Id] then return false, tostring(wo) .. " missing" end end
return true
end)
check("Equipment wielded by you", function()
for _, wo in ipairs(equip) do if wo.WielderId ~= C.Id then return false, tostring(wo) .. " wielder " .. wo.WielderId end end
return true
end)
note("Containers()", function() local c = C.Containers(); return #c .. " side packs" end)
note("InventoryCount('Pyreal')", function() return C.InventoryCount("Pyreal") end)
check("Inventory filter by function", function()
local packs = C.Inventory(function(wo) return wo.ObjectClass == ObjectClass.Container end)
return #packs == #C.Containers(), #packs .. " containers"
end)
-- ── World ─────────────────────────────────────────────────────────────────
section("game.World")
check("Get(me)", function() local wo = W.Get(C.Id); return wo ~= nil and wo.Name == C.Name, tostring(wo) end)
check("World[id] / Exists", function() return W[C.Id] ~= nil and W.Exists(C.Id) and not W.Exists(1) end)
check("Get('0x...') string id", function() return W.Get(string.format("0x%08X", C.Id)) ~= nil end)
local all, land = {}, {}
check("GetAll()", function() all = W.GetAll(); return #all > #inv, #all .. " known objects" end)
check("GetLandscape()", function() land = W.GetLandscape(); return #land > 0, #land .. " on the landscape" end)
check("GetInventory() matches Character.Inventory()", function()
local wi = W.GetInventory()
return #wi == #inv, "World " .. #wi .. ", Character " .. #inv
end)
check("Landscape has no carried items", function()
for _, wo in ipairs(land) do
if wo.ContainerId ~= 0 or wo.WielderId ~= 0 or wo.Id == C.Id then return false, tostring(wo) end
end
return true
end)
check("class name filter == class number filter", function()
local a, b = #W.GetAll("Monster"), #W.GetAll(ObjectClass.Monster)
return a == b, a .. " monsters"
end)
note("portals nearby", function() return #W.GetLandscape(ObjectClass.Portal) end)
note("players nearby", function() return #W.GetLandscape(ObjectClass.Player) end)
local near
check("GetNearest(function)", function()
near = W.GetNearest(function(wo) return wo.Name ~= "" end)
return near ~= nil, near and (tostring(near) .. " at " .. string.format("%.1f", near.DistanceTo(C.Weenie)) .. " m") or "nothing"
end)
if near then
check("WorldObject basics", function()
return type(near.ObjectClass) == "number" and type(near.ObjectClassName) == "string" and near.WeenieClassId > 0,
near.ObjectClassName .. ", wcid " .. near.WeenieClassId
end)
check("WorldObject Position", function()
local p = near.Position
return p ~= nil and p.Landcell ~= 0, p and string.format("%.2f%s %.2f%s, z %.1f, cell 0x%08X",
math.abs(p.NS), p.NS >= 0 and "N" or "S", math.abs(p.EW), p.EW >= 0 and "E" or "W", p.Z, p.Landcell) or "nil"
end)
check("tostring / equality", function()
local again = W.Get(near.Id)
return again == near and tostring(near):find("0x") ~= nil, tostring(near)
end)
end
local item = inv[1]
for _, wo in ipairs(inv) do if wo.ObjectClass ~= ObjectClass.Container and wo.WielderId == 0 then item = wo; break end end
if item then
check("inventory item properties", function()
return item.ContainerId ~= 0 and item.StackSize >= 1,
tostring(item) .. " in " .. tostring(item.Container) .. ", stack " .. item.StackSize .. ", value " .. item:Value(IntId.Value) .. ", burden " .. item.Burden
end)
note("item IntValue(IntId.Value) / HasAppraisalData", function() return tostring(item.IntValue(IntId.Value, -1)) .. " / " .. tostring(item.HasAppraisalData) end)
end
local packs = C.Containers()
if #packs > 0 then
check("pack Items()", function() local it = packs[1].Items(); return type(it) == "table", tostring(packs[1]) .. ": " .. #it .. " items" end)
end
note("Selected", function() return tostring(W.Selected) end)
-- ── Actions ───────────────────────────────────────────────────────────────
section("game.Actions")
local t0 = clock()
local sl = await(A.Sleep(300))
check("Sleep + await", function() return sl.Success and sl.IsFinished and clock() - t0 >= 280, (clock() - t0) .. " ms, Error " .. sl.Error end)
check("bad argument is an error", function() return not pcall(A.ObjectUse) end)
local selectedEvent = false
W.OnSelected.Once(function(e) selectedEvent = (item ~= nil and e.ObjectId == item.Id) end)
if item then
local cbFired = false
local a = await(A.ObjectSelect(item, function(act) cbFired = true end))
check("ObjectSelect", function() return a.Success and W.Selected ~= nil and W.Selected.Id == item.Id, "Error " .. a.Error .. " " .. a.ErrorDetails end)
check("action callback ran", function() return waitfor(function() return cbFired end, 2000) end)
check("World.OnSelected fired", function() return waitfor(function() return selectedEvent end, 2000) end)
local m = await(item.Select())
check("WorldObject:Select() method", function() return m.Success, m.Error end)
end
local apTarget = near or item
if apTarget then
local ap = await(A.ObjectAppraise(apTarget))
check("ObjectAppraise", function() return ap.Success, tostring(apTarget) .. ", Error " .. ap.Error .. " " .. ap.ErrorDetails end)
note("appraised HasAppraisalData", function() return tostring(apTarget.HasAppraisalData) end)
end
-- Combat mode: to a fighting mode that suits what you wield, then back.
local startMode = C.CombatMode
local fightMode = CombatMode.Melee
for _, wo in ipairs(equip) do
if wo.ObjectClass == ObjectClass.MissileWeapon then fightMode = CombatMode.Missile end
if wo.ObjectClass == ObjectClass.WandStaffOrb then fightMode = CombatMode.Magic end
end
local modeEvents = 0
C.OnCombatModeChanged.Add(function(e) modeEvents = modeEvents + 1 end)
local same = await(A.SetCombatMode(startMode))
check("SetCombatMode(current) is immediate", function() return same.Success, same.Error end)
local target = startMode == CombatMode.NonCombat and fightMode or CombatMode.NonCombat
local m1 = await(A.SetCombatMode(target))
check("SetCombatMode -> " .. CombatMode[target], function() return m1.Success and C.CombatMode == target, "now " .. C.CombatModeName .. ", Error " .. m1.Error .. " " .. m1.ErrorDetails end)
local m2 = await(A.SetCombatMode(startMode))
check("SetCombatMode back -> " .. CombatMode[startMode], function() return m2.Success and C.CombatMode == startMode, "now " .. C.CombatModeName .. ", Error " .. m2.Error end)
check("OnCombatModeChanged fired", function() return waitfor(function() return modeEvents >= 2 end, 2000), modeEvents .. " events" end)
local long = A.Sleep(5000)
long.Cancel()
await(long)
check("Cancel()", function() return long.IsFinished and not long.Success and long.Error == "Cancelled", long.Error end)
local s1, s2 = A.Sleep(100), A.Sleep(100)
local all2 = await(A.RunAllOrdered({ s1, s2 }))
check("RunAllOrdered", function() return all2.Success and s1.Success and s2.Success, all2.Error end)
check("ActionQueue", function() return type(Q.Count) == "number" and type(Q.IsBusy) == "boolean", "count " .. Q.Count .. ", busy " .. tostring(Q.IsBusy) end)
-- ── Events ────────────────────────────────────────────────────────────────
section("Events")
local ticks = 0
local function onTick() ticks = ticks + 1 end
game.OnTick.Add(onTick)
sleep(1000)
game.OnTick.Remove(onTick)
check("game.OnTick", function() return ticks >= 5, ticks .. " ticks in 1 s" end)
local after = ticks
sleep(300)
-- A handler call started in the same tick as Remove may still finish once.
check("Event Remove", function() return ticks <= after + 1, (ticks - after) .. " late call(s)" end)
local untilN = 0
game.OnTick.Until(function() untilN = untilN + 1; return untilN >= 3 end)
sleep(600)
check("Event Until stops at true", function() return untilN == 3, untilN end)
local vitalEvents = 0
C.OnVitalChanged.Add(function() vitalEvents = vitalEvents + 1 end)
note("Character.OnVitalChanged (seen so far)", function() return vitalEvents end)
local chatSeen = false
W.OnChatText.Once(function(e) chatSeen = true end)
chat("[smoke-test] chat line to your own window")
note("World.OnChatText from chat()", function() return tostring(waitfor(function() return chatSeen end, 1500)) end)
-- ── RynthAi (rynth.ai module and v1 globals) ──────────────────────────────
section("RynthAi")
if not ai.Available then
out("INFO", "rynth.ai", "RynthAi not loaded, skipped")
else
out("PASS", "rynth.ai Available")
check("SettingNames()", function() local n = ai.SettingNames(); return #n > 0, #n .. " settings" end)
note("MacroRunning", function() return tostring(ai.MacroRunning) end)
note("Evaluate('getcharintprop[25]') (level)", function() return tostring(ai.Evaluate("getcharintprop[25]")) end)
if near then note("ai.DistanceTo(nearest)", function() return ai.DistanceTo(near) end) end
note("ai.FindNearest('Portal', true)", function() local wo, d = ai.FindNearest("Portal", true); return tostring(wo) .. " " .. tostring(d) end)
-- v1 globals (me, expr, ...) come from RynthAi too.
check("v1 me.name", function() return me.name == C.Name end)
check("v1 me.maxhealth", function() return me.maxhealth == C.MaxHealth, "me " .. tostring(me.maxhealth) .. ", Character " .. C.MaxHealth .. " (base " .. C.Vitals.Health.Base .. ")" end)
check("v1 me.maxmana", function() return me.maxmana == C.MaxMana, "me " .. tostring(me.maxmana) .. ", Character " .. C.MaxMana end)
end
-- ── Command, results ──────────────────────────────────────────────────────
section("Done")
game.RegisterCommand("/smoketest", function(args)
local line = "INFO /smoketest " .. args .. ": command received"
print(line)
local prev = fs.ReadText("results.txt") or ""
fs.WriteText("results.txt", prev .. "\n" .. line)
if args == "stop" then
print("stopping via stop()")
stop()
else
chat("[smoke-test] pong: " .. args)
end
end)
local summary = string.format("%d passed, %d failed, %d info", counts.PASS, counts.FAIL, counts.INFO)
lines[#lines + 1] = ""
lines[#lines + 1] = summary
print(summary)
local ok, err = fs.WriteText("results.txt", table.concat(lines, "\n"))
if not ok then print("couldn't write results.txt: " .. tostring(err)) end
chat("[smoke-test] " .. summary .. ". Now try /smoketest hello, then /smoketest stop.")

View file

@ -0,0 +1,93 @@
-- world-demo: a tour of game.World and WorldObject.
-- Prints what's around you and in your packs, then keeps listening for
-- objects, tells and selection changes until you press Stop.
local World = game.World
-- ObjectClass numbers (Decal/UtilityBelt order). A filter can also be the exact
-- class name as a string: World.GetLandscape("Monster").
local MONSTER, PORTAL, CORPSE = 5, 14, 27
local function where(wo)
local p = wo.Position
if not p then return "(no position)" end
return ("%.1f%s %.1f%s"):format(math.abs(p.NS), p.NS >= 0 and "N" or "S",
math.abs(p.EW), p.EW >= 0 and "E" or "W")
end
-- Around you ----------------------------------------------------------------
local me = World.Get(game.CharacterId)
if not me then print("Log in first.") return end
print("You are " .. tostring(me) .. " at " .. where(me))
local monsters = World.GetLandscape(MONSTER)
print(#monsters .. " monster(s) nearby")
for _, m in ipairs(monsters) do
print((" %-28s %6.1f m wcid %d"):format(m.Name, me:DistanceTo(m), m.WeenieClassId))
end
local portal = World.GetNearest("Portal") -- by class name
if portal then
print("Nearest portal: " .. portal.Name .. " at " .. where(portal))
end
-- A function filter: corpses within 30 m.
local close = World.GetLandscape(function(wo)
return wo.ObjectClass == CORPSE and me:DistanceTo(wo) < 30
end)
print(#close .. " corpse(s) within 30 m")
-- Your stuff ----------------------------------------------------------------
local inv = World.GetInventory()
print(#inv .. " item(s) in your packs (game.Character.Inventory() adds what you wear)")
local burden = 0
for _, item in ipairs(inv) do burden = burden + item.Burden end
print("Burden of appraised items: " .. burden)
for _, pack in ipairs(World.GetInventory(function(wo) return wo.ObjectClass == 10 end)) do
print((" %s holds %d item(s)"):format(pack.Name, #pack:Items()))
end
local tapers = World.GetInventory("Taper") -- a name substring
for _, p in ipairs(tapers) do
print((" %s x%d (stack prop 12 = %d)"):format(p.Name, p.StackSize, p:IntValue(12, 1)))
end
-- The selection ---------------------------------------------------------------
local sel = World.Selected
if sel then
print("Selected: " .. tostring(sel) .. ", class " .. sel.ObjectClass ..
", appraised: " .. tostring(sel.HasAppraisalData))
end
-- Events ------------------------------------------------------------------------
World.OnObjectCreated.Add(function(e)
local wo = e.Object
if wo and wo.ObjectClass == PORTAL then
print("A portal appeared: " .. wo.Name)
end
end)
World.OnObjectReleased.Add(function(e)
-- e.ObjectId only: the object is already gone.
end)
World.OnTell.Add(function(e)
print(os.date("%H:%M") .. " tell from " .. e.SenderName .. ": " .. e.Message)
end)
World.OnSelected.Add(function(e)
if e.Object then
print("You selected " .. e.Object.Name .. " (" .. where(e.Object) .. ")")
end
end)
-- Stops listening to chat after the first line that contains "stop demo".
World.OnChatText.Until(function(e)
if e.Message:find("stop demo") then
print("OnChatText handler removed.")
return true
end
end)
print("Listening for portals, tells and selections. Press Stop to end.")

View file

@ -0,0 +1,46 @@
-- xp-tracker.lua: a tracker window (script windows): XP gained, XP per hour, kills and a
-- health bar, with a Reset button that has a tooltip.
-- Needs RynthCore API v71 (engine) with ImGui on. Start it with /lua start xp-tracker;
-- close the window with its X and bring it back from the bar's Scripts button or with
-- /lua hud show xp-tracker/XP Tracker.
--
-- OnRender runs about 20 times a second while the window is shown and records what to
-- draw; the engine draws it every frame. ImGui.Button returns true on the pass after the
-- click. OnPreRender runs just before OnRender in the same pass: it is where the window's
-- first size goes (FirstUseEver: only until the player moves or sizes it).
local views = require("views")
local ImGui = require("imgui")
if not views.Available then
print("Script windows aren't available here (engine older than API v71, or ImGui is off).")
end
local hud = views.Huds.CreateHud("XP Tracker")
-- Shown at start. Leave this line out to let the player's last choice (the X, the bar's
-- Scripts menu) decide instead.
hud.Visible = true
local startXp, startAt, kills = game.Character.TotalExperience, clock(), 0
on("kill", function() kills = kills + 1 end) -- v1 event; v2 has no kill event yet
hud.OnPreRender.Add(function()
ImGui.SetNextWindowSize(Vector2.new(240, 130), ImGuiCond.FirstUseEver)
end)
hud.OnRender.Add(function()
local c = game.Character
local gained = c.TotalExperience - startXp
local hours = math.max((clock() - startAt) / 3600000, 1 / 3600)
ImGui.Text("XP gained: " .. math.floor(gained))
ImGui.Text("XP / hour: " .. math.floor(gained / hours))
ImGui.Text("Kills: " .. kills)
ImGui.ProgressBar(c.Health / math.max(c.MaxHealth, 1), Vector2.new(-1, 0),
c.Health .. " / " .. c.MaxHealth)
if ImGui.Button("Reset") then
startXp, startAt, kills = c.TotalExperience, clock(), 0
end
ImGui.SetItemTooltip("Start counting again from now")
end)
print("XP Tracker open. /lua stop xp-tracker closes it.")

View file

@ -0,0 +1,685 @@
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using MoonSharp.Interpreter;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthLua;
/// <summary>
/// ActionError names (UtilityBelt's enum, same names). Scripts see them as strings:
/// <c>action.Error == "TooBusy"</c> or <c>action.Error == ActionError.TooBusy</c>.
/// </summary>
internal static class ActionErrors
{
public const string None = "None";
public const string TimedOut = "TimedOut";
public const string ServerError = "ServerError";
public const string NotLoggedIn = "NotLoggedIn";
public const string CantUseOnItself = "CantUseOnItself";
public const string TargetItemNotInInventoryOrLandscape = "TargetItemNotInInventoryOrLandscape";
public const string SourceItemNotInInventory = "SourceItemNotInInventory";
public const string InvalidTargetItem = "InvalidTargetItem";
public const string InvalidSourceObject = "InvalidSourceObject";
public const string ItemAlreadyWielded = "ItemAlreadyWielded";
public const string TooEncumbered = "TooEncumbered";
public const string MustBeInPeaceMode = "MustBeInPeaceMode";
public const string YouCantPickThatUp = "YouCantPickThatUp";
public const string InvalidInventoryLocation = "InvalidInventoryLocation";
public const string YouDontKnowThatSpell = "YouDontKnowThatSpell";
public const string MissingComponents = "MissingComponents";
public const string UnknownSpellId = "UnknownSpellId";
public const string SpellFizzled = "SpellFizzled";
public const string InvalidTargetObject = "InvalidTargetObject";
public const string Exception = "Exception";
public const string SourceObjectTooFar = "SourceObjectTooFar";
public const string Cancelled = "Cancelled";
public const string NPCDoesntKnowWhatToDoWithThat = "NPCDoesntKnowWhatToDoWithThat";
public const string TooBusy = "TooBusy";
public const string CantSplitThisObject = "CantSplitThisObject";
public const string ObjectSplitAmountTooBig = "ObjectSplitAmountTooBig";
public const string InvalidCombatMode = "InvalidCombatMode";
public const string OnCooldown = "OnCooldown";
public const string PreconditionFailed = "PreconditionFailed";
/// <summary>UtilityBelt's full list (numbering order), exposed as the ActionError global.</summary>
public static readonly string[] All =
{
"None", "TimedOut", "ServerError", "NotLoggedIn", "NotEnoughUnassignedExperience", "AlreadyMaxed",
"TooMuchSpendExperience", "NotYourCharacter", "NotTrained", "YouDoNotPassCraftingRequirements",
"ItemBeingTraded", "YouHaveBeenInPKBattleTooRecently", "CantUseOnItself", "TargetItemNotInInventoryOrLandscape",
"SourceItemNotInInventory", "SourceItemNotInInventoryOrLandscape", "InvalidTargetItem", "InvalidSourceObject",
"ItemAlreadyWielded", "TooEncumbered", "MustBeInPeaceMode", "YouCantPickThatUp", "InvalidInventoryLocation",
"YouDontKnowThatSpell", "MissingComponents", "UnknownSpellId", "SpellFizzled", "AlreadyInFellow",
"MustBeInFellow", "NotTheLeader", "NotInFellow", "MemberDoesntExist", "FellowshipIsFull", "FellowshipClosed",
"AlreadyRecruited", "FellowshipRecruitBusy", "FellowshipLocked", "InvalidTargetObject", "UnknownCommand",
"CharacterDoesntExist", "CharacterPendingDelete", "NotAtCharacterSelect", "PreconditionFailed", "NoUst",
"UnsalvageableItem", "NoTradePartner", "Exception", "AlreadyTrained", "CantAdvanceSkill",
"NotEnoughAvailableCredits", "SkillDoesntExist", "NotInAnAllegiance", "AlreadyInAnAllegiance",
"SourceObjectTooFar", "NoActions", "Cancelled", "NPCDoesntKnowWhatToDoWithThat", "TooBusy", "VendorNotOpen",
"VendorDoesntHaveThisItem", "VendorDoesntHaveEnoughOfThisItem", "CantSplitThisObject",
"ObjectSplitAmountTooBig", "InvalidSpellLevel", "InvalidCombatMode", "OnCooldown",
};
/// <summary>Errors that mean "nothing happened, try again": retried up to MaxRetryCount.</summary>
public static bool IsTemporary(string error) => error is TooBusy or SpellFizzled;
}
/// <summary>
/// AC's WeenieError codes (the server's UseDone, WeenieError, WeenieErrorWithString and
/// InventoryServerSaveFailed carry them; engine API v70+) mapped to UtilityBelt's ActionError
/// names. Numbers and names from ACE's WeenieError / WeenieErrorWithString enums. Codes not
/// listed here are left alone as refusals (many are notices: "You have entered the channel",
/// PK status, ...); a nonzero UseDone code that isn't listed is a ServerError.
/// </summary>
internal static class WeenieErrors
{
public enum Kind : byte { General, Spell, Combat }
private readonly record struct Entry(string Name, string Error, Kind Kind);
private static readonly Dictionary<uint, Entry> Map = new()
{
// General
[0x001D] = new("YoureTooBusy", ActionErrors.TooBusy, Kind.General),
[0x001E] = new("_IsTooBusyToAcceptGifts", ActionErrors.TooBusy, Kind.General),
[0x0020] = new("IllegalInventoryTransaction", ActionErrors.InvalidInventoryLocation, Kind.General),
[0x002A] = new("YouAreTooEncumbered", ActionErrors.TooEncumbered, Kind.General),
[0x002B] = new("_CannotCarryAnymore", ActionErrors.InvalidInventoryLocation, Kind.General),
[0x0036] = new("ActionCancelled", ActionErrors.Cancelled, Kind.General),
[0x0037] = new("ObjectGone", ActionErrors.InvalidSourceObject, Kind.General),
[0x0038] = new("NoObject", ActionErrors.InvalidSourceObject, Kind.General),
[0x0039] = new("CantGetThere", ActionErrors.SourceObjectTooFar, Kind.General),
[0x003A] = new("Dead", ActionErrors.ServerError, Kind.General),
[0x003E] = new("YouAreTooTiredToDoThat", ActionErrors.ServerError, Kind.General),
[0x0045] = new("TooManyActions", ActionErrors.TooBusy, Kind.General),
[0x03EE] = new("TheContainerIsClosed", ActionErrors.InvalidInventoryLocation, Kind.General),
[0x03EF] = new("_IsNotAcceptingGiftsRightNow", ActionErrors.ServerError, Kind.General),
[0x03F0] = new("InvalidInventoryLocation", ActionErrors.InvalidInventoryLocation, Kind.General),
[0x03F1] = new("ChangeCombatModeFailure", ActionErrors.InvalidCombatMode, Kind.General),
[0x03F2] = new("FullInventoryLocation", ActionErrors.InvalidInventoryLocation, Kind.General),
[0x03F3] = new("ConflictingInventoryLocation", ActionErrors.InvalidInventoryLocation, Kind.General),
[0x03F5] = new("BeWieldedFailure", ActionErrors.InvalidInventoryLocation, Kind.General),
[0x03F6] = new("BeDroppedFailure", ActionErrors.ServerError, Kind.General),
[0x0426] = new("AttunedItem", ActionErrors.ServerError, Kind.General),
[0x0427] = new("YouCannotMergeDifferentStacks", ActionErrors.InvalidTargetItem, Kind.General),
[0x0428] = new("YouCannotMergeEnchantedItems", ActionErrors.InvalidTargetItem, Kind.General),
[0x0437] = new("YouDoNotPassCraftingRequirements", "YouDoNotPassCraftingRequirements", Kind.General),
[0x043A] = new("YouMustBeInPeaceModeToTrade", ActionErrors.MustBeInPeaceMode, Kind.General),
[0x043B] = new("YouAreNotTrainedInThatTradeSkill", "NotTrained", Kind.General),
[0x043E] = new("YouHaveSolvedThisQuestTooRecently", ActionErrors.OnCooldown, Kind.General),
[0x0453] = new("TradeItemBeingTraded", "ItemBeingTraded", Kind.General),
[0x046A] = new("_DoesntKnowWhatToDoWithThat", ActionErrors.NPCDoesntKnowWhatToDoWithThat, Kind.General),
[0x0498] = new("YouHaveMovedTooFar", ActionErrors.SourceObjectTooFar, Kind.General),
[0x04A7] = new("YouHaveBeenTeleportedTooRecently", ActionErrors.OnCooldown, Kind.General),
[0x04B2] = new("KeyDoesntFitThisLock", ActionErrors.InvalidTargetItem, Kind.General),
[0x04B3] = new("LockUsedTooRecently", ActionErrors.OnCooldown, Kind.General),
[0x04B4] = new("YouArentTrainedInLockpicking", "NotTrained", Kind.General),
[0x04BE] = new("YouDoNotOwnThatItem", ActionErrors.SourceItemNotInInventory, Kind.General),
[0x04BF] = new("The_WasNotSuitableForSalvaging", "UnsalvageableItem", Kind.General),
[0x04C2] = new("ItemsAttemptingToSalvageIsInvalid", "UnsalvageableItem", Kind.General),
[0x04C3] = new("YouCannotSalvageItemsInTrading", "ItemBeingTraded", Kind.General),
[0x04CF] = new("_CannotAcceptStackedItems", ActionErrors.ServerError, Kind.General),
[0x04FC] = new("YouArentTrainedInHealing", "NotTrained", Kind.General),
[0x04FE] = new("YouCantHealThat", ActionErrors.InvalidTargetObject, Kind.General),
[0x0500] = new("YouArentReadyToHeal", ActionErrors.OnCooldown, Kind.General),
[0x0506] = new("CantDoThatTradeInProgress", "ItemBeingTraded", Kind.General),
[0x058D] = new("YouCannotUseThatItem", ActionErrors.ServerError, Kind.General),
// Spell (casting and its aftermath)
[0x03FA] = new("YouveAttemptedAnImpossibleSpellPath", ActionErrors.ServerError, Kind.Spell),
[0x03FC] = new("MagicInvalidSpellType", ActionErrors.UnknownSpellId, Kind.Spell),
[0x03FE] = new("YouDontKnowThatSpell", ActionErrors.YouDontKnowThatSpell, Kind.Spell),
[0x03FF] = new("IncorrectTargetType", ActionErrors.InvalidTargetObject, Kind.Spell),
[0x0400] = new("YouDontHaveAllTheComponents", ActionErrors.MissingComponents, Kind.Spell),
[0x0401] = new("YouDontHaveEnoughManaToCast", ActionErrors.ServerError, Kind.Spell),
[0x0402] = new("YourSpellFizzled", ActionErrors.SpellFizzled, Kind.Spell),
[0x0403] = new("YourSpellTargetIsMissing", ActionErrors.InvalidTargetObject, Kind.Spell),
[0x0404] = new("YourProjectileSpellMislaunched", ActionErrors.ServerError, Kind.Spell),
[0x0406] = new("MagicTargetOutOfRange", ActionErrors.ServerError, Kind.Spell),
[0x0407] = new("YourSpellCannotBeCastOutside", ActionErrors.ServerError, Kind.Spell),
[0x0408] = new("YourSpellCannotBeCastInside", ActionErrors.ServerError, Kind.Spell),
[0x0409] = new("MagicGeneralFailure", ActionErrors.ServerError, Kind.Spell),
[0x040A] = new("YouAreUnpreparedToCastASpell", ActionErrors.InvalidCombatMode, Kind.Spell),
[0x042C] = new("TargetNotAcquired", ActionErrors.InvalidTargetObject, Kind.Spell),
[0x04C5] = new("YourAllegianceRankIsTooLowToUseMagic", ActionErrors.ServerError, Kind.Spell),
[0x04C7] = new("YourArcaneLoreIsTooLowToUseMagic", ActionErrors.ServerError, Kind.Spell),
[0x04C8] = new("ItemDoesntHaveEnoughMana", ActionErrors.ServerError, Kind.Spell),
[0x04CC] = new("YouHaveBeenInPKBattleTooRecently", "YouHaveBeenInPKBattleTooRecently", Kind.Spell),
[0x04EB] = new("YouCantDoThatWhileInTheAir", ActionErrors.ServerError, Kind.Spell),
[0x004E] = new("YouFailToAffect_YouCannotAffectAnyone", ActionErrors.ServerError, Kind.Spell),
[0x004F] = new("YouFailToAffect_TheyCannotBeHarmed", ActionErrors.ServerError, Kind.Spell),
[0x0050] = new("YouFailToAffect_WithBeneficialSpells", ActionErrors.ServerError, Kind.Spell),
[0x0051] = new("YouFailToAffect_YouAreNotPK", ActionErrors.ServerError, Kind.Spell),
[0x0052] = new("YouFailToAffect_TheyAreNotPK", ActionErrors.ServerError, Kind.Spell),
[0x0053] = new("YouFailToAffect_NotSamePKType", ActionErrors.ServerError, Kind.Spell),
[0x0054] = new("YouFailToAffect_AcrossHouseBoundary", ActionErrors.ServerError, Kind.Spell),
[0x04FA] = new("_IsAnInvalidTarget", ActionErrors.InvalidTargetObject, Kind.Spell),
[0x0509] = new("_HasNoSpellTargets", ActionErrors.InvalidTargetObject, Kind.Spell),
[0x050A] = new("YouHaveNoTargetsForSpellOf_", ActionErrors.InvalidTargetObject, Kind.Spell),
// Combat (never an action's failure: RynthAi's or the player's fighting)
[0x003D] = new("YouChargedTooFar", ActionErrors.ServerError, Kind.Combat),
[0x03F7] = new("YouAreTooFatiguedToAttack", ActionErrors.ServerError, Kind.Combat),
[0x03F8] = new("YouAreOutOfAmmunition", ActionErrors.ServerError, Kind.Combat),
[0x03F9] = new("YourAttackMisfired", ActionErrors.ServerError, Kind.Combat),
[0x042A] = new("CurrentlyAttacking", ActionErrors.ServerError, Kind.Combat),
[0x042B] = new("MissileAttackNotOk", ActionErrors.ServerError, Kind.Combat),
[0x042D] = new("ImpossibleShot", ActionErrors.ServerError, Kind.Combat),
[0x042E] = new("BadWeaponSkill", ActionErrors.ServerError, Kind.Combat),
[0x042F] = new("UnwieldFailure", ActionErrors.ServerError, Kind.Combat),
[0x0430] = new("LaunchFailure", ActionErrors.ServerError, Kind.Combat),
[0x0431] = new("ReloadFailure", ActionErrors.ServerError, Kind.Combat),
[0x0550] = new("MissileOutOfRange", ActionErrors.ServerError, Kind.Combat),
};
/// <summary>Whether this code is a known refusal, and of which kind.</summary>
public static bool TryKind(uint code, out Kind kind)
{
if (Map.TryGetValue(code, out Entry e)) { kind = e.Kind; return true; }
kind = Kind.General;
return false;
}
/// <summary>The ActionError name for a refusal code (ServerError when it isn't mapped).</summary>
public static string ActionError(uint code) => Map.TryGetValue(code, out Entry e) ? e.Error : ActionErrors.ServerError;
/// <summary>"0x0402 YourSpellFizzled" (just the number when it isn't mapped).</summary>
public static string Describe(uint code) => Map.TryGetValue(code, out Entry e) ? $"0x{code:X4} {e.Name}" : $"0x{code:X4}";
}
/// <summary>UtilityBelt's ActionType priorities (higher runs first).</summary>
internal static class ActionPriority
{
public const int Immediate = int.MaxValue;
public const int Wield = 20000, RestoreHealth = 19000, RestoreStamina = 18000, RestoreMana = 17000,
LoginLogoff = 16000, Vendor = 15500, Trade = 15000, Combat = 14000, CastSpell = 13000, Navigation = 12000,
Fellow = 11000, Allegiance = 10000, Inventory = 9000, Misc = 8000;
public static readonly (string Name, int Value)[] All =
{
("Immediate", Immediate), ("Wield", Wield), ("RestoreHealth", RestoreHealth), ("RestoreStamina", RestoreStamina),
("RestoreMana", RestoreMana), ("LoginLogoff", LoginLogoff), ("Vendor", Vendor), ("Trade", Trade),
("Combat", Combat), ("CastSpell", CastSpell), ("Navigation", Navigation), ("Fellow", Fellow),
("Allegiance", Allegiance), ("Inventory", Inventory), ("Misc", Misc),
};
public static bool TryParse(string name, out int value)
{
foreach (var (n, v) in All)
if (n.Equals(name, StringComparison.OrdinalIgnoreCase)) { value = v; return true; }
value = 0;
return false;
}
}
/// <summary>Per-call options (UB's ActionOptions): <c>{ Priority, TimeoutMilliseconds, MaxRetryCount, SkipChecks, Name }</c>.</summary>
internal struct ActionOptions
{
public int? Priority;
public int? TimeoutMs;
public int? MaxRetryCount;
public bool SkipChecks;
public string? Name;
}
internal enum ActionPhase { Queued, Waiting, Sent, RetryWait, Finished }
/// <summary>What a chat line tells the running action.</summary>
internal enum ChatHint { None, Fail, CastOk, GiveOk }
/// <summary>
/// AC's own messages that end (or refuse) an action. Anchored at the start of the line where
/// the wording is known, and lines that are somebody talking are ignored first, so a player
/// saying "You're too busy!" doesn't fail anything.
/// </summary>
internal static class ActionChat
{
private static readonly Regex CannotUseWith = new(@"^Cannot use the .+ with the ", RegexOptions.CultureInvariant);
private static readonly Regex CannotBeUsedOn = new(@"^The .+ cannot be used on ", RegexOptions.CultureInvariant);
private static readonly Regex CombinedWithItself = new(@"^The .+ cannot be combined with itself", RegexOptions.CultureInvariant);
private static readonly Regex MustWield = new(@"^You must (wield|contain) the .+ to use it", RegexOptions.CultureInvariant);
public static bool IsSpeech(string t) =>
t.StartsWith('[') || t.Contains(" says, \"", StringComparison.Ordinal) || t.Contains(" tells you, \"", StringComparison.Ordinal)
|| t.StartsWith("You say, \"", StringComparison.Ordinal) || t.StartsWith("You tell ", StringComparison.Ordinal)
|| t.Contains(" says to you, \"", StringComparison.Ordinal);
/// <summary>
/// Classifies a line; for <see cref="ChatHint.Fail"/> also the ActionError, whether only a
/// cast can cause it, and whether it is <paramref name="coded"/>: the text AC shows for a
/// WeenieError code that engine API v70+ reports directly (see WeenieErrors). An action
/// that reads those codes ignores coded lines, since the line may be about somebody
/// else's action (RynthAi's cast, the player's own clicks); the rest are plain server text
/// with no code behind them, so chat stays the only signal for those.
/// </summary>
public static ChatHint Classify(string t, out string error, out bool spellOnly, out bool coded)
{
error = ActionErrors.None;
spellOnly = false;
coded = true;
if (Starts(t, "You're too busy") || Starts(t, "You are too busy")) return Fail(ActionErrors.TooBusy, out error);
if (Starts(t, "Unable to move to object")) return Fail(ActionErrors.SourceObjectTooFar, out error);
if (Starts(t, "You are too encumbered")) return Fail(ActionErrors.TooEncumbered, out error);
if (Has(t, "doesn't know what to do with that") || Has(t, "does not know what to do with that"))
return Fail(ActionErrors.NPCDoesntKnowWhatToDoWithThat, out error);
if (Has(t, "cannot carry any more")) return Fail(ActionErrors.InvalidInventoryLocation, out error);
coded = false;
if (Starts(t, "You can't pick that up") || Starts(t, "You cannot pick that up") || Starts(t, "You can not pick that up"))
return Fail(ActionErrors.YouCantPickThatUp, out error);
if (Starts(t, "Cannot pick that up and wield it while not at peace") || Has(t, "must be in peace mode"))
return Fail(ActionErrors.MustBeInPeaceMode, out error);
if (CombinedWithItself.IsMatch(t)) return Fail(ActionErrors.CantUseOnItself, out error);
if (CannotUseWith.IsMatch(t) || CannotBeUsedOn.IsMatch(t)) return Fail(ActionErrors.InvalidTargetItem, out error);
if (MustWield.IsMatch(t)) return Fail(ActionErrors.SourceItemNotInInventory, out error);
if (Has(t, "have used this item too recently")) return Fail(ActionErrors.OnCooldown, out error);
if (Has(t, " is not accepting ")) return Fail(ActionErrors.ServerError, out error);
if (Has(t, "enough pack space")) return Fail(ActionErrors.InvalidInventoryLocation, out error);
if (Starts(t, "You give ") || Starts(t, "You hand over ") || Starts(t, "You allow ")) return ChatHint.GiveOk;
// Casting (RynthAi's buff/combat code matches the same phrases).
if (Starts(t, "You cast ") || Has(t, "resists your spell")) return ChatHint.CastOk;
spellOnly = true;
if (Starts(t, "You must specify")) return Fail(ActionErrors.InvalidTargetObject, out error); // the client's own check
coded = true;
if (Has(t, "fizzle") || Has(t, "your spell failed")) return Fail(ActionErrors.SpellFizzled, out error);
if (Has(t, "missing some required") || Has(t, "have all the components for this spell") || Starts(t, "You do not have the"))
return Fail(ActionErrors.MissingComponents, out error);
if (Has(t, "don't know that spell") || Has(t, "do not know that spell")) return Fail(ActionErrors.YouDontKnowThatSpell, out error);
if (Has(t, "lack the mana") || Has(t, "enough mana to cast")) return Fail(ActionErrors.ServerError, out error);
if (Has(t, "is out of range") || Starts(t, "You fail to affect")) return Fail(ActionErrors.ServerError, out error);
spellOnly = false;
coded = false;
return ChatHint.None;
}
private static ChatHint Fail(string e, out string error) { error = e; return ChatHint.Fail; }
private static bool Starts(string t, string p) => t.StartsWith(p, StringComparison.OrdinalIgnoreCase);
private static bool Has(string t, string p) => t.Contains(p, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// One queued action and its Lua object. The Lua table's fields are RAW fields, rewritten on
/// every state change (<c>await</c> polls the raw <c>IsFinished</c>):
/// ActionId, ActionType, Name, ScriptName, Priority, Options, IsStarted, IsRunning, IsFinished,
/// Success, Error, ErrorDetails, Result, StartedAt, FinishedAt (clock() milliseconds),
/// CurrentRetryCount, plus the action's own arguments (ObjectId, TargetId, SpellId, ...).
///
/// Lifecycle: Queued → Waiting (gates: logged in, not in portal space, no cast/use gesture
/// animating) → checks → Send → Sent (watch completion signals) → Finished. A temporary error
/// (TooBusy, SpellFizzled) goes to RetryWait and back to Waiting, up to MaxRetryCount. The
/// timeout counts from the start of each attempt.
/// </summary>
internal abstract class LuaAction
{
private static long _nextId;
protected readonly RynthLuaPlugin P;
protected RynthCoreHost Host => P.ActHost;
public readonly long ActionId = ++_nextId;
public readonly ScriptContext Ctx;
public Table T = null!;
public DynValue Callback = DynValue.Nil;
public string Name = string.Empty;
public int Priority;
public int TimeoutMs;
public int MaxRetryCount;
public bool SkipChecks;
public ActionPhase Phase { get; private set; } = ActionPhase.Queued;
/// <summary>The RunAllOrdered action running this one (null: the queue runs it).</summary>
public LuaAction? Owner;
public int Retry;
public long StartedAt, FinishedAt, AttemptStart, SentAt, RetryAt;
public bool Success;
public string Error = ActionErrors.None;
public string ErrorDetails = string.Empty;
public DynValue Result = DynValue.Nil;
private bool _settling;
private long _settleAt;
private DynValue _settleResult = DynValue.Nil;
protected LuaAction(RynthLuaPlugin p, ScriptContext ctx)
{
P = p;
Ctx = ctx;
}
/// <summary>"ObjectUse", "CastSpell", ... (the game.Actions function that made it).</summary>
public abstract string Kind { get; }
protected virtual int DefaultPriority => ActionPriority.Misc;
protected virtual int DefaultTimeoutMs => 5000;
protected virtual int DefaultMaxRetryCount => 3;
/// <summary>Runs beside the queue (Sleep, InvokeChat) instead of taking the one action slot.</summary>
public virtual bool Immediate => false;
/// <summary>UB's ActionType: the kind's priority category (Immediate for the ones beside the queue).</summary>
public int Category => Immediate ? ActionPriority.Immediate : DefaultPriority;
protected virtual bool NeedsLogin => true;
/// <summary>Waits for AC to be free (no cast/use gesture animating, not in portal space) before sending.</summary>
protected virtual bool NeedsIdle => false;
/// <summary>Preconditions (skipped with SkipChecks). Returns an ActionError name, or null when fine.</summary>
protected virtual string? Check(out string details) { details = string.Empty; return null; }
/// <summary>Issues the command. Return false after calling Fail (or Succeed, when there was nothing to do).</summary>
protected abstract bool Send(long now);
/// <summary>Called every tick while Sent: look at the completion signals.</summary>
protected virtual void Poll(long now) { }
/// <summary>A chat line while Sent. Default: general failures fail the action (spell-only ones don't).</summary>
protected virtual void OnChat(string text, ChatHint hint, string error, bool spellOnly)
{
if (hint == ChatHint.Fail && !spellOnly) Fail(error, text);
}
/// <summary>Extra raw fields of this action type (ObjectId, SpellId, ...).</summary>
protected virtual void DescribeFields(Table t) { }
public void ApplyOptions(ActionOptions o)
{
Priority = o.Priority ?? DefaultPriority;
TimeoutMs = o.TimeoutMs ?? DefaultTimeoutMs;
MaxRetryCount = Math.Max(0, o.MaxRetryCount ?? DefaultMaxRetryCount);
SkipChecks = o.SkipChecks;
Name = string.IsNullOrEmpty(o.Name) ? Kind : o.Name!;
if (Immediate && o.Priority == null) Priority = ActionPriority.Immediate;
}
/// <summary>Makes the Lua object in <paramref name="s"/> (raw fields + Cancel/Await).</summary>
public void CreateTable(Script s, DynValue makeAwait)
{
var t = new Table(s);
T = t;
t.Set("ActionId", DynValue.NewNumber(ActionId));
// UB: ActionType is the priority category (ActionType.Inventory, ...); Kind is the
// game.Actions function that made it ("ObjectUse").
t.Set("ActionType", DynValue.NewNumber(Category));
t.Set("Kind", DynValue.NewString(Kind));
t.Set("Name", DynValue.NewString(Name));
t.Set("ScriptName", DynValue.NewString(Ctx.Name));
t.Set("__rynth_action", DynValue.True);
var opts = new Table(s);
opts.Set("Priority", DynValue.NewNumber(Priority));
opts.Set("TimeoutMilliseconds", DynValue.NewNumber(TimeoutMs));
opts.Set("MaxRetryCount", DynValue.NewNumber(MaxRetryCount));
opts.Set("SkipChecks", DynValue.NewBoolean(SkipChecks));
opts.Set("Name", DynValue.NewString(Name));
t.Set("Options", DynValue.NewTable(opts));
DescribeFields(t);
t.Set("Cancel", DynValue.NewCallback((c, a) =>
{
Cancel("cancelled by the script");
return DynValue.Nil;
}));
if (makeAwait.Type == DataType.Function)
{
try { t.Set("Await", s.Call(makeAwait, DynValue.NewTable(t))); }
catch { }
}
var mt = new Table(s);
mt["__tostring"] = DynValue.NewCallback((c, a) => DynValue.NewString(ToString()));
t.MetaTable = mt;
Sync();
}
public override string ToString()
{
string state = Phase switch
{
ActionPhase.Queued => "queued",
ActionPhase.Finished => Success ? "succeeded" : $"failed: {Error}",
_ => "running",
};
return $"Action {Name} #{ActionId} ({state})";
}
/// <summary>Rewrites the state fields of the Lua table.</summary>
protected void Sync()
{
Table? t = T;
if (t == null) return;
bool finished = Phase == ActionPhase.Finished;
t.Set("Priority", DynValue.NewNumber(Priority));
t.Set("IsStarted", DynValue.NewBoolean(Phase != ActionPhase.Queued));
t.Set("IsRunning", DynValue.NewBoolean(Phase is ActionPhase.Waiting or ActionPhase.Sent or ActionPhase.RetryWait));
t.Set("Success", DynValue.NewBoolean(Success));
t.Set("Error", DynValue.NewString(Error));
t.Set("ErrorDetails", DynValue.NewString(ErrorDetails));
t.Set("Result", Result);
t.Set("CurrentRetryCount", DynValue.NewNumber(Retry));
t.Set("StartedAt", StartedAt > 0 ? DynValue.NewNumber(StartedAt) : DynValue.Nil);
t.Set("FinishedAt", finished ? DynValue.NewNumber(FinishedAt) : DynValue.Nil);
t.Set("IsFinished", DynValue.NewBoolean(finished)); // last: await reads this one
}
// ── Running ─────────────────────────────────────────────────────────────
/// <summary>One tick of this action (the queue's current action, an immediate one, or a RunAllOrdered step).</summary>
public void Step(long now)
{
if (Phase == ActionPhase.Finished) return;
if (Phase == ActionPhase.Queued)
{
Phase = ActionPhase.Waiting;
StartedAt = now;
AttemptStart = now;
Sync();
}
if (Phase == ActionPhase.RetryWait)
{
if (now < RetryAt) return;
Phase = ActionPhase.Waiting;
AttemptStart = now;
Sync();
}
if (Phase == ActionPhase.Waiting)
{
if (NeedsLogin && !SkipChecks && (P.GameState != "InGame" || Host.GetPlayerId() == 0))
{
Fail(ActionErrors.NotLoggedIn, "not in game");
return;
}
if (!Ready())
{
if (TimeoutMs > 0 && now - AttemptStart >= TimeoutMs)
Fail(ActionErrors.TimedOut, $"the client stayed busy for {TimeoutMs} ms, the action was never sent");
return;
}
if (!SkipChecks)
{
string? err = Check(out string details);
if (err != null) { Fail(err, details); return; }
}
_settling = false;
SentAt = now;
Phase = ActionPhase.Sent;
MarkServerCodes();
if (!Send(now)) return;
Sync();
return; // signals are looked at from the next tick
}
if (Phase == ActionPhase.Sent)
{
if (CheckRefusal()) return;
Poll(now);
if (Phase != ActionPhase.Sent) return;
if (_settling && now >= _settleAt) { Succeed(_settleResult); return; }
if (TimeoutMs > 0 && now - AttemptStart >= TimeoutMs)
Fail(ActionErrors.TimedOut, $"no completion signal within {TimeoutMs} ms");
}
}
private bool Ready()
{
if (!NeedsIdle || SkipChecks) return true;
if (Host.HasIsPortaling && Host.IsPortaling()) return false;
if (Host.HasGetCastBusyState && Host.GetCastBusyState() != 0) return false;
return true;
}
/// <summary>
/// A chat line reached the queue: only a Sent action listens. An action that reads the
/// server's codes (API v70+) skips the failure lines those codes already report
/// (<paramref name="coded"/>): they may be about another action.
/// </summary>
public virtual void HandleChat(string text, ChatHint hint, string error, bool spellOnly, bool coded)
{
if (Phase != ActionPhase.Sent) return;
if (hint == ChatHint.Fail && coded && _codes) return;
OnChat(text, hint, error, spellOnly);
}
// ── Server outcome codes (engine API v70+) ──────────────────────────────
// The engine keeps the last UseDone (seq + WeenieError code) and the last refusal
// (WeenieError / WeenieErrorWithString / InventoryServerSaveFailed with its item). Both
// counters are recorded when the action is sent; anything newer is about this attempt or
// about something else running at the same time, which IsMyRefusal sorts out.
private bool _codes;
private int _useDoneSeq, _refusalSeq;
/// <summary>This attempt reads the server's codes (the action wants them and the engine has them).</summary>
protected bool ServerCodes => _codes;
/// <summary>Whether the action reads the server's codes when the engine offers them.</summary>
protected virtual bool WatchesServerCodes => false;
/// <summary>
/// Whether a refusal the server sent while this action ran is about it. eventType 0x028A /
/// 0x028B (WeenieError, WithString) or 0x00A0 (InventoryServerSaveFailed, objectId = the item).
/// </summary>
protected virtual bool IsMyRefusal(uint eventType, uint code, uint objectId) => false;
private void MarkServerCodes()
{
_codes = WatchesServerCodes && Host.HasGetLastUseDone && Host.HasGetLastWeenieError;
if (!_codes) return;
Host.TryGetLastUseDone(out _useDoneSeq, out _);
Host.TryGetLastWeenieError(out _refusalSeq, out _, out _, out _);
}
/// <summary>A UseDone that arrived since the send (or the last call): true, with its code (0 = done).</summary>
protected bool NextUseDone(out uint error)
{
error = 0;
if (!_codes || !Host.TryGetLastUseDone(out int seq, out uint e) || seq == _useDoneSeq) return false;
_useDoneSeq = seq;
error = e;
return true;
}
/// <summary>A new refusal that IsMyRefusal claims fails (or retries) the action.</summary>
private bool CheckRefusal()
{
if (!_codes || !Host.TryGetLastWeenieError(out int seq, out uint code, out uint evt, out uint obj) || seq == _refusalSeq)
return false;
_refusalSeq = seq;
if (code == 0 || !IsMyRefusal(evt, code, obj)) return false;
FailWithCode(code, evt == 0x00A0 ? "the server refused it" : "the server said no");
return true;
}
/// <summary>Fails with the ActionError for a WeenieError code; ErrorDetails names the code.</summary>
protected void FailWithCode(uint code, string what) => Fail(WeenieErrors.ActionError(code), $"{what} ({WeenieErrors.Describe(code)})");
/// <summary>A general (not spell, not combat) refusal code this table knows.</summary>
protected static bool IsGeneralRefusal(uint code) => WeenieErrors.TryKind(code, out var k) && k == WeenieErrors.Kind.General;
/// <summary>
/// A completion signal arrived; succeed after <paramref name="ms"/> unless a failure line
/// comes first (AC's error text and the UseDone can arrive in either order).
/// </summary>
protected void SucceedAfter(long now, int ms, DynValue? result = null)
{
if (_settling) return;
_settling = true;
_settleAt = now + ms;
_settleResult = result ?? DynValue.Nil;
}
protected bool Settling => _settling;
public void Succeed(DynValue? result = null) => Complete(true, ActionErrors.None, string.Empty, result ?? DynValue.Nil);
public void Fail(string error, string details)
{
if (Phase == ActionPhase.Finished) return;
if (ActionErrors.IsTemporary(error) && Retry < MaxRetryCount)
{
Retry++;
_settling = false;
Phase = ActionPhase.RetryWait;
// Back off before trying again (AC stays busy for a moment after a refusal).
RetryAt = Environment.TickCount64 + (error == ActionErrors.TooBusy ? 400L * Retry : 250L);
ErrorDetails = details;
Sync();
return;
}
Complete(false, error, details, DynValue.Nil);
}
public void Cancel(string details)
{
if (Phase == ActionPhase.Finished) return;
Complete(false, ActionErrors.Cancelled, details, DynValue.Nil);
}
protected virtual void Complete(bool success, string error, string details, DynValue result)
{
if (Phase == ActionPhase.Finished) return;
Phase = ActionPhase.Finished;
Success = success;
Error = error;
ErrorDetails = details ?? string.Empty;
Result = result;
FinishedAt = Environment.TickCount64;
if (StartedAt == 0) StartedAt = FinishedAt;
Sync();
P.OnActionFinished(this);
if (Callback.Type == DataType.Function && Ctx.Host.Loaded)
Ctx.Host.Start(Callback, new[] { DynValue.NewTable(T) });
}
// ── Helpers for the action types ────────────────────────────────────────
protected uint PlayerId => Host.GetPlayerId();
protected bool Exists(uint id) => id != 0 && Host.TryGetObjectName(id, out string n) && n.Length > 0;
protected bool TryOwnership(uint id, out uint container, out uint wielder)
{
container = wielder = 0;
return Host.HasGetObjectOwnershipInfo && Host.TryGetObjectOwnershipInfo(id, out container, out wielder, out _);
}
protected uint ContainerOf(uint id) => TryOwnership(id, out uint c, out _) ? c : 0;
protected uint WielderOf(uint id) => TryOwnership(id, out _, out uint w) ? w : 0;
/// <summary>In the character's inventory (main pack, a side pack, or wielded). True when the engine can't tell.</summary>
protected bool IsMine(uint id)
{
uint me = PlayerId;
if (id == 0 || me == 0) return false;
if (id == me) return true;
if (!TryOwnership(id, out uint c, out uint w)) return Host.HasGetObjectOwnershipInfo ? false : true;
if (w == me || c == me) return true;
return c != 0 && TryOwnership(c, out uint c2, out _) && c2 == me;
}
protected int StackSize(uint id) => Host.TryGetObjectIntProperty(id, 12, out int v) && v > 0 ? v : 1;
protected int MaxStackSize(uint id) => Host.TryGetObjectIntProperty(id, 11, out int v) ? v : 0;
protected uint Wcid(uint id) => Host.TryGetObjectWcid(id, out uint w) ? w : 0;
protected DynValue Wrap(uint id)
{
Script? s = Ctx.Host.Lua;
return s == null || id == 0 ? DynValue.Nil : P.WrapObject(s, Ctx, id);
}
protected static string Hex(uint id) => $"0x{id:X8}";
protected string Describe(uint id) => Host.TryGetObjectName(id, out string n) && n.Length > 0 ? $"{n} ({Hex(id)})" : Hex(id);
}

View file

@ -0,0 +1,735 @@
using System;
using System.Collections.Generic;
using MoonSharp.Interpreter;
using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthLua;
/// <summary>An action on one world object (and maybe a target).</summary>
internal abstract class ObjectAction : LuaAction
{
public readonly uint ObjectId;
public readonly uint TargetId;
protected ObjectAction(RynthLuaPlugin p, ScriptContext ctx, uint objectId, uint targetId) : base(p, ctx)
{
ObjectId = objectId;
TargetId = targetId;
}
protected override void DescribeFields(Table t)
{
t.Set("ObjectId", DynValue.NewNumber(ObjectId));
t.Set("TargetId", DynValue.NewNumber(TargetId));
}
protected string? NeedObject(out string details)
{
details = string.Empty;
if (Exists(ObjectId)) return null;
details = $"no object {Hex(ObjectId)} (not known to the client)";
return ActionErrors.InvalidSourceObject;
}
protected string? NeedMine(out string details)
{
details = string.Empty;
if (IsMine(ObjectId)) return null;
details = $"{Describe(ObjectId)} isn't in your inventory";
return ActionErrors.SourceItemNotInInventory;
}
protected bool EngineRefused(string what)
{
Fail(ActionErrors.Exception, $"the engine didn't accept the {what} (missing SDK function, bad id or full pack)");
return false;
}
// Object actions read the server's codes (API v70+): an inventory refusal names its
// item, so that one is certain; general refusals (too busy, too encumbered, can't get
// there, ...) count too. Spell and combat codes never do (RynthAi's casts and fights).
protected override bool WatchesServerCodes => true;
protected override bool IsMyRefusal(uint eventType, uint code, uint objectId)
=> eventType == 0x00A0 ? objectId == ObjectId : IsGeneralRefusal(code);
}
/// <summary>
/// ObjectUse / ObjectUseOn. Done on the server's UseDone (the counter moves), the item being
/// used up, or portal space; a failure line within 250 ms of it wins. On API v70+ the
/// UseDone's own code says whether it worked (nonzero fails with that code's ActionError).
/// </summary>
internal sealed class UseAction : ObjectAction
{
private readonly bool _on;
private int _seq;
public UseAction(RynthLuaPlugin p, ScriptContext ctx, uint objectId, uint targetId, bool on) : base(p, ctx, objectId, targetId) => _on = on;
public override string Kind => _on ? "ObjectUseOn" : "ObjectUse";
protected override bool NeedsIdle => true;
protected override int DefaultTimeoutMs => 10000; // using something far away walks there first
protected override string? Check(out string details)
{
string? e = NeedObject(out details);
if (e != null) return e;
if (TargetId != 0)
{
if (TargetId == ObjectId) { details = "can't use an object on itself"; return ActionErrors.CantUseOnItself; }
if (!Exists(TargetId)) { details = $"no target {Hex(TargetId)}"; return ActionErrors.InvalidTargetObject; }
}
return null;
}
protected override bool Send(long now)
{
_seq = Host.GetUseDoneSeq();
bool ok = TargetId == 0
? Host.HasUseObject && Host.UseFor(ObjectId, "Script", $"{Ctx?.Name ?? "?"}: game.Actions.ObjectUse", UseKind.Asked)
: Host.HasUseObjectOn && Host.UseOnFor(ObjectId, TargetId, "Script", $"{Ctx?.Name ?? "?"}: game.Actions.ObjectUse on a target", UseKind.Asked);
return ok || EngineRefused("use");
}
protected override bool IsMyRefusal(uint eventType, uint code, uint objectId)
=> eventType == 0x00A0 ? objectId == ObjectId || (TargetId != 0 && objectId == TargetId) : IsGeneralRefusal(code);
protected override void Poll(long now)
{
if (ServerCodes)
{
// Once settling, a later UseDone belongs to something else.
if (!Settling && NextUseDone(out uint err))
{
if (err != 0) { FailWithCode(err, "the server's UseDone"); return; }
SucceedAfter(now, 250);
return;
}
}
else if (Host.HasUseDoneSeq && Host.GetUseDoneSeq() != _seq) { SucceedAfter(now, 250); return; }
if (!Exists(ObjectId)) { SucceedAfter(now, 250); return; } // used up (potion, food, kit)
if (Host.HasIsPortaling && Host.IsPortaling()) { SucceedAfter(now, 0); return; }
// Opening a chest / corpse: it's the open container now.
if (TargetId == 0 && Host.HasGetGroundContainerId && Host.GetGroundContainerId() == ObjectId) { SucceedAfter(now, 150); return; }
// No UseDone signal on this engine: the gesture finished and nothing complained.
if (!Host.HasUseDoneSeq && now - SentAt >= 1000 && Host.GetCastBusyState() == 0) SucceedAfter(now, 250);
}
}
/// <summary>ObjectGive: done when the item leaves the inventory (or its stack shrinks), or "You give ...".</summary>
internal sealed class GiveAction : ObjectAction
{
private int _stack;
public GiveAction(RynthLuaPlugin p, ScriptContext ctx, uint objectId, uint targetId) : base(p, ctx, objectId, targetId) { }
public override string Kind => "ObjectGive";
protected override int DefaultPriority => ActionPriority.Inventory;
protected override bool NeedsIdle => true;
protected override int DefaultTimeoutMs => 10000; // walks to the target first
protected override string? Check(out string details)
{
string? e = NeedObject(out details) ?? NeedMine(out details);
if (e != null) return e;
if (TargetId == 0 || TargetId == PlayerId || !Exists(TargetId)) { details = $"no one to give to ({Hex(TargetId)})"; return ActionErrors.InvalidTargetObject; }
return null;
}
protected override bool Send(long now)
{
_stack = StackSize(ObjectId);
bool ok = Host.HasGiveObjectTo ? Host.GiveObjectTo(ObjectId, TargetId, 0)
: Host.HasMoveItemExternal && Host.MoveItemExternal(ObjectId, TargetId, Math.Max(1, _stack));
return ok || EngineRefused("give");
}
protected override void Poll(long now)
{
if (!Exists(ObjectId) || !IsMine(ObjectId) || StackSize(ObjectId) < _stack) SucceedAfter(now, 150);
}
protected override void OnChat(string text, ChatHint hint, string error, bool spellOnly)
{
if (hint == ChatHint.GiveOk) { Succeed(); return; }
base.OnChat(text, hint, error, spellOnly);
}
}
/// <summary>
/// ObjectMove: into a pack of yours (merging into a stack there when <c>stack</c>), picking
/// something up, or putting it into another container. Done when the item is in the target
/// container (or, for a merge, when the source stack shrinks or disappears).
/// </summary>
internal sealed class MoveAction : ObjectAction
{
private readonly int _slot;
private readonly bool _stack;
private bool _merge;
private int _stackBefore;
private readonly bool _pickup;
public MoveAction(RynthLuaPlugin p, ScriptContext ctx, uint objectId, uint containerId, int slot, bool stack)
: base(p, ctx, objectId, containerId)
{
_slot = Math.Max(0, slot);
_stack = stack;
_pickup = !IsMine(objectId);
}
public override string Kind => "ObjectMove";
protected override int DefaultPriority => ActionPriority.Inventory;
protected override bool NeedsIdle => true;
protected override int DefaultTimeoutMs => _pickup ? 10000 : 5000;
protected override void DescribeFields(Table t)
{
base.DescribeFields(t);
t.Set("Slot", DynValue.NewNumber(_slot));
t.Set("Stack", DynValue.NewBoolean(_stack));
}
protected override string? Check(out string details)
{
string? e = NeedObject(out details);
if (e != null) return e;
if (TargetId == 0) { details = "no container (use Drop() to put it on the ground)"; return ActionErrors.InvalidInventoryLocation; }
if (TargetId != PlayerId && !Exists(TargetId)) { details = $"no container {Hex(TargetId)}"; return ActionErrors.TargetItemNotInInventoryOrLandscape; }
return null;
}
protected override bool Send(long now)
{
if (TryOwnership(ObjectId, out uint c, out uint w) && c == TargetId && w == 0) { Succeed(Wrap(ObjectId)); return false; }
uint me = PlayerId;
bool mine = IsMine(ObjectId);
bool targetMine = TargetId == me || IsMine(TargetId);
_stackBefore = StackSize(ObjectId);
bool ok;
if (mine && targetMine)
{
uint into = _stack ? FindMergeStack() : 0;
if (into != 0 && Host.HasMergeStackInternal)
{
_merge = true;
ok = Host.MergeStackInternal(ObjectId, into);
}
else ok = Host.HasMoveItemInternal && Host.MoveItemInternal(ObjectId, TargetId, _slot, Math.Max(1, _stackBefore));
}
else if (!mine)
ok = Host.HasMoveItemExternal && Host.MoveItemExternal(ObjectId, TargetId, 0); // pick up (RynthAi's loot path)
else
ok = Host.HasMoveItemExternal && Host.MoveItemExternal(ObjectId, TargetId, Math.Max(1, _stackBefore));
if (ok) return true;
Fail(ActionErrors.InvalidInventoryLocation, "the engine refused the move (is the pack full?)");
return false;
}
/// <summary>A stack of the same kind in the target container with room left.</summary>
private uint FindMergeStack()
{
uint wcid = Wcid(ObjectId);
if (wcid == 0 || MaxStackSize(ObjectId) <= 1) return 0;
var buf = new uint[256];
int n = Host.GetContainerContents(TargetId, buf);
for (int i = 0; i < n; i++)
{
uint id = buf[i];
if (id == ObjectId || Wcid(id) != wcid) continue;
int max = MaxStackSize(id);
if (max > 1 && StackSize(id) < max) return id;
}
return 0;
}
protected override void Poll(long now)
{
if (_merge)
{
if (!Exists(ObjectId) || StackSize(ObjectId) < _stackBefore) Succeed();
return;
}
if (TryOwnership(ObjectId, out uint c, out uint w) && c == TargetId && w == 0) { Succeed(Wrap(ObjectId)); return; }
if (!Exists(ObjectId)) Succeed(); // merged into a stack on arrival
}
}
/// <summary>
/// ObjectSplit: a new stack of <c>amount</c> into a container. Done when the source stack
/// shrinks; Result is the new stack (found as a new object of the same kind in the container).
/// </summary>
internal sealed class SplitAction : ObjectAction
{
private readonly int _amount;
private readonly int _slot;
private int _stackBefore;
private uint _into;
private HashSet<uint> _before = new();
private long _splitSeenAt;
public SplitAction(RynthLuaPlugin p, ScriptContext ctx, uint objectId, uint containerId, int amount, int slot)
: base(p, ctx, objectId, containerId)
{
_amount = amount;
_slot = Math.Max(0, slot);
}
public override string Kind => "ObjectSplit";
protected override int DefaultPriority => ActionPriority.Inventory;
protected override bool NeedsIdle => true;
protected override void DescribeFields(Table t)
{
base.DescribeFields(t);
t.Set("NewStackSize", DynValue.NewNumber(_amount));
t.Set("Slot", DynValue.NewNumber(_slot));
}
protected override string? Check(out string details)
{
string? e = NeedObject(out details) ?? NeedMine(out details);
if (e != null) return e;
int stack = StackSize(ObjectId);
if (stack <= 1) { details = $"{Describe(ObjectId)} isn't a stack"; return ActionErrors.CantSplitThisObject; }
if (_amount >= stack) { details = $"can't split {_amount} off a stack of {stack}"; return ActionErrors.ObjectSplitAmountTooBig; }
return null;
}
protected override bool Send(long now)
{
_into = TargetId != 0 ? TargetId : ContainerOf(ObjectId);
if (_into == 0) _into = PlayerId;
_stackBefore = StackSize(ObjectId);
_before = Contents(_into);
bool ok = Host.HasSplitStackInternal && Host.SplitStackInternal(ObjectId, _into, _slot, _amount);
return ok || EngineRefused("split");
}
private HashSet<uint> Contents(uint container)
{
var buf = new uint[256];
int n = Host.GetContainerContents(container, buf);
var set = new HashSet<uint>();
for (int i = 0; i < n; i++) set.Add(buf[i]);
return set;
}
protected override void Poll(long now)
{
if (_splitSeenAt == 0 && StackSize(ObjectId) < _stackBefore) _splitSeenAt = now;
uint wcid = Wcid(ObjectId);
foreach (uint id in Contents(_into))
{
if (id == ObjectId || _before.Contains(id)) continue;
if (wcid != 0 && Wcid(id) != wcid) continue;
T.Set("NewStackObjectId", DynValue.NewNumber(id)); // UB's field
Succeed(Wrap(id));
return;
}
// The stack shrank but the new one didn't show up in the container yet: give it a moment.
if (_splitSeenAt != 0 && now - _splitSeenAt >= 1500) Succeed();
}
}
/// <summary>ObjectDrop: done when the item isn't in the inventory anymore.</summary>
internal sealed class DropAction : ObjectAction
{
public DropAction(RynthLuaPlugin p, ScriptContext ctx, uint objectId) : base(p, ctx, objectId, 0) { }
public override string Kind => "ObjectDrop";
protected override int DefaultPriority => ActionPriority.Inventory;
protected override bool NeedsIdle => true;
protected override string? Check(out string details) => NeedObject(out details) ?? NeedMine(out details);
protected override bool Send(long now)
=> (Host.HasMoveItemExternal && Host.MoveItemExternal(ObjectId, 0, 0)) || EngineRefused("drop");
protected override void Poll(long now)
{
if (!Exists(ObjectId) || !IsMine(ObjectId)) Succeed();
}
}
/// <summary>
/// ObjectWield: with a slot (an EquipMask number) the item goes into that slot, as dragging it
/// onto the paperdoll does (engine API v70+ WieldItem; the server checks the slot against the
/// item). Without a slot, or on an older engine, it uses the item and AC wields it in its
/// default slot. Done when you wield it; a refusal of the item fails it.
/// </summary>
internal sealed class WieldAction : ObjectAction
{
private readonly uint _slot;
public WieldAction(RynthLuaPlugin p, ScriptContext ctx, uint objectId, uint slot) : base(p, ctx, objectId, 0) => _slot = slot;
public override string Kind => "ObjectWield";
protected override int DefaultPriority => ActionPriority.Wield;
protected override bool NeedsIdle => true;
protected override void DescribeFields(Table t)
{
base.DescribeFields(t);
t.Set("Slot", DynValue.NewNumber(_slot));
}
protected override string? Check(out string details)
{
string? e = NeedObject(out details);
if (e != null) return e;
if (WielderOf(ObjectId) == PlayerId) { details = $"{Describe(ObjectId)} is already wielded"; return ActionErrors.ItemAlreadyWielded; }
// ValidLocations (IntId 9): the slots the item can go into, when the client knows them.
if (_slot != 0 && Host.HasWieldItem && Host.TryGetObjectIntProperty(ObjectId, 9, out int valid) && valid != 0
&& (unchecked((uint)valid) & _slot) == 0)
{
details = $"{Describe(ObjectId)} can't go in slot 0x{_slot:X8} (it fits 0x{unchecked((uint)valid):X8})";
return ActionErrors.InvalidInventoryLocation;
}
return null;
}
protected override bool Send(long now)
{
if (_slot != 0 && Host.HasWieldItem)
return Host.WieldItem(ObjectId, _slot) || EngineRefused("wield");
return (Host.HasUseObject && Host.UseFor(ObjectId, "Script", $"{Ctx?.Name ?? "?"}: game.Actions.ObjectWield", UseKind.Asked)) || EngineRefused("wield");
}
protected override void Poll(long now)
{
if (WielderOf(ObjectId) == PlayerId) Succeed(Wrap(ObjectId));
}
}
/// <summary>ObjectSelect: done when the client's selection is the object.</summary>
internal sealed class SelectAction : ObjectAction
{
public SelectAction(RynthLuaPlugin p, ScriptContext ctx, uint objectId) : base(p, ctx, objectId, 0) { }
public override string Kind => "ObjectSelect";
protected override bool WatchesServerCodes => false; // no server round trip
protected override string? Check(out string details) => NeedObject(out details);
protected override bool Send(long now) => (Host.HasSelectItem && Host.SelectItem(ObjectId)) || EngineRefused("select");
protected override void OnChat(string text, ChatHint hint, string error, bool spellOnly) { } // no server round trip
protected override void Poll(long now)
{
if (Host.GetSelectedItemId() == ObjectId) Succeed(Wrap(ObjectId));
}
}
/// <summary>ObjectAppraise: RequestId; done when new appraisal data for the object arrives. Result is the object.</summary>
internal sealed class AppraiseAction : ObjectAction
{
private long _idTime;
private bool _had;
public AppraiseAction(RynthLuaPlugin p, ScriptContext ctx, uint objectId) : base(p, ctx, objectId, 0) { }
public override string Kind => "ObjectAppraise";
protected override bool WatchesServerCodes => false;
protected override string? Check(out string details) => NeedObject(out details);
protected override void OnChat(string text, ChatHint hint, string error, bool spellOnly) { } // not a use: AC's "busy" lines aren't about it
protected override bool Send(long now)
{
_idTime = Host.GetLastIdTime(ObjectId);
_had = Host.HasAppraisalData(ObjectId);
return (Host.HasRequestId && Host.RequestId(ObjectId)) || EngineRefused("appraisal request");
}
protected override void Poll(long now)
{
long t = Host.GetLastIdTime(ObjectId);
if (t != 0 && t != _idTime) { Succeed(Wrap(ObjectId)); return; }
if (!_had && Host.HasAppraisalData(ObjectId)) { Succeed(Wrap(ObjectId)); return; }
// The id time has a one-second grain: a re-appraisal within the same second looks
// unchanged. Data that was already there is good enough after a short wait.
if (_had && t == _idTime && now - SentAt >= 1500) Succeed(Wrap(ObjectId));
}
}
/// <summary>
/// CastSpell: done on the server's UseDone (or "You cast ..."); fizzles and "too busy" are
/// retried (MaxRetryCount), missing components / unknown spell fail at once. On API v70+ the
/// outcome comes from the server's codes instead of chat: the UseDone's code, and a spell
/// refusal (a fizzle is WeenieError 0x402 followed by UseDone(0)).
/// </summary>
internal sealed class CastSpellAction : LuaAction
{
public readonly int SpellId;
public readonly uint TargetId;
private int _seq;
private bool _sawBusy;
public CastSpellAction(RynthLuaPlugin p, ScriptContext ctx, int spellId, uint targetId) : base(p, ctx)
{
SpellId = spellId;
TargetId = targetId;
}
public override string Kind => "CastSpell";
protected override int DefaultPriority => ActionPriority.CastSpell;
protected override bool NeedsIdle => true;
// A recall's gesture and teleport can run past 5 s before portal space even starts ("no
// completion signal within 5000 ms" while the character did recall, 10-02). An ordinary cast
// still finishes on its UseDone in a second or two; this only bounds a cast that never answers.
protected override int DefaultTimeoutMs => 15000;
private uint _startLandblock;
protected override void DescribeFields(Table t)
{
t.Set("SpellId", DynValue.NewNumber(SpellId));
t.Set("TargetId", DynValue.NewNumber(TargetId));
}
protected override string? Check(out string details)
{
details = string.Empty;
if (SpellId <= 0) { details = $"spell id {SpellId}"; return ActionErrors.UnknownSpellId; }
if (P.KnowsSpellIfLoaded((uint)SpellId) == false)
{ details = $"spell {SpellId} isn't in your spellbook"; return ActionErrors.YouDontKnowThatSpell; }
if (Host.HasGetCurrentCombatMode && Host.GetCurrentCombatMode() != 8)
{ details = "not in magic mode (game.Actions.SetCombatMode(\"Magic\") first)"; return ActionErrors.InvalidCombatMode; }
if (TargetId != 0 && !Exists(TargetId)) { details = $"no target {Hex(TargetId)}"; return ActionErrors.InvalidTargetObject; }
return null;
}
protected override bool Send(long now)
{
_seq = Host.GetUseDoneSeq();
_sawBusy = false;
_startLandblock = Host.TryGetPlayerPose(out uint cell, out _, out _, out _, out _, out _, out _, out _) ? cell >> 16 : 0;
if (Host.HasCastSpell && Host.CastSpell(TargetId, SpellId)) return true;
// The engine holds one pending cast at a time: another one queued (RynthAi buffing right
// after a recall, say) refuses this one for a moment. That's "busy, try again", not a
// failure (10-02: "the engine didn't accept the cast"); TooBusy retries with a back-off.
if (Host.HasCastSpell) { Fail(ActionErrors.TooBusy, "the engine's cast slot was busy (another cast was queued)"); return false; }
Fail(ActionErrors.Exception, "this engine can't cast");
return false;
}
protected override bool WatchesServerCodes => true;
// Spell refusals, and "too busy" (which the server may also send as a WeenieError).
protected override bool IsMyRefusal(uint eventType, uint code, uint objectId)
=> eventType != 0x00A0 && (code == 0x001D || (WeenieErrors.TryKind(code, out var k) && k == WeenieErrors.Kind.Spell));
protected override void Poll(long now)
{
// A recall (Lifestone Recall, portal ties, Aphus Lassel...) ends in a teleport, and the
// server's UseDone can come only after portal space - 6-7 s on Aelrynth, past the 5 s
// timeout ("no completion signal within 5000 ms" on game.Actions.CastSpell(1635, ...),
// 10-02). Portal space means the cast worked.
if (Host.HasIsPortaling && Host.IsPortaling())
{
if (!Settling) SucceedAfter(now, 100);
return;
}
// ...or already landed somewhere else (portal space missed between two ticks).
if (_startLandblock != 0 && Host.TryGetPlayerPose(out uint cellNow, out _, out _, out _, out _, out _, out _, out _)
&& cellNow != 0 && (cellNow >> 16) != _startLandblock)
{
if (!Settling) SucceedAfter(now, 100);
return;
}
if (ServerCodes)
{
// A fizzle's WeenieError comes before its UseDone(0), and refusals are checked
// before Poll, so a short settle is enough.
if (!Settling && NextUseDone(out uint err))
{
if (err != 0) FailWithCode(err, "the server's UseDone");
else SucceedAfter(now, 100);
}
return;
}
if (Host.HasUseDoneSeq)
{
if (Host.GetUseDoneSeq() != _seq) SucceedAfter(now, 300);
return;
}
// No UseDone on this engine: the cast gesture started and ended.
int busy = Host.GetCastBusyState();
if (busy != 0) _sawBusy = true;
else if (_sawBusy) SucceedAfter(now, 500);
}
protected override void OnChat(string text, ChatHint hint, string error, bool spellOnly)
{
// With the server's codes, "You cast ..." may be somebody else's cast (RynthAi): the
// UseDone decides. Coded failure lines never get here then (HandleChat drops them).
if (hint == ChatHint.CastOk) { if (!ServerCodes) Succeed(); return; }
if (hint == ChatHint.Fail) Fail(error, text);
}
}
/// <summary>SetCombatMode: done when the client reports the mode.</summary>
internal sealed class CombatModeAction : LuaAction
{
public readonly int Mode;
public CombatModeAction(RynthLuaPlugin p, ScriptContext ctx, int mode) : base(p, ctx) => Mode = mode;
public override string Kind => "SetCombatMode";
protected override int DefaultPriority => ActionPriority.Combat;
protected override bool NeedsIdle => true;
protected override void DescribeFields(Table t)
{
t.Set("CombatMode", DynValue.NewNumber(Mode));
t.Set("CombatModeName", DynValue.NewString(LuaEnums.CombatModeName(Mode)));
}
protected override bool Send(long now)
{
if (Host.GetCurrentCombatMode() == Mode) { Succeed(); return false; }
if (Host.HasChangeCombatMode && Host.ChangeCombatMode(Mode)) return true;
Fail(ActionErrors.Exception, "the engine didn't accept the combat mode change");
return false;
}
protected override void Poll(long now)
{
if (Host.GetCurrentCombatMode() == Mode) Succeed();
}
}
/// <summary>Sleep(ms): an immediate action that finishes after ms (handy inside RunAllOrdered).</summary>
internal sealed class SleepAction : LuaAction
{
public readonly int Milliseconds;
private long _until;
public SleepAction(RynthLuaPlugin p, ScriptContext ctx, int ms) : base(p, ctx) => Milliseconds = Math.Max(0, ms);
public override string Kind => "Sleep";
public override bool Immediate => true;
protected override bool NeedsLogin => false;
protected override int DefaultTimeoutMs => 0;
protected override int DefaultMaxRetryCount => 0;
protected override void DescribeFields(Table t) => t.Set("Milliseconds", DynValue.NewNumber(Milliseconds));
protected override bool Send(long now)
{
_until = now + Milliseconds;
return true;
}
protected override void Poll(long now)
{
if (now >= _until) Succeed();
}
}
/// <summary>InvokeChat(text): as if typed in the chat bar (commands too). Immediate.</summary>
internal sealed class InvokeChatAction : LuaAction
{
public readonly string Text;
public InvokeChatAction(RynthLuaPlugin p, ScriptContext ctx, string text) : base(p, ctx) => Text = text;
public override string Kind => "InvokeChat";
public override bool Immediate => true;
protected override bool NeedsLogin => false;
protected override int DefaultMaxRetryCount => 0;
protected override void DescribeFields(Table t) => t.Set("Text", DynValue.NewString(Text));
protected override bool Send(long now)
{
if (Host.HasInvokeChatParser && Host.InvokeChatParser(Text)) { Succeed(DynValue.True); return false; }
Fail(ActionErrors.Exception, Host.HasInvokeChatParser ? "the chat parser didn't take the line" : "this engine has no chat parser function");
return false;
}
}
/// <summary>
/// RunAllOrdered(list): runs the given actions one after another as a single queue entry.
/// Actions still waiting in the queue are taken out of it; one that already started is waited
/// for. Stops at the first failure (the rest are cancelled) with that action's Error; Result
/// is the list.
/// </summary>
internal sealed class RunAllOrderedAction : LuaAction
{
private readonly List<LuaAction?> _children;
private readonly List<Table> _tables;
private int _index;
public RunAllOrderedAction(RynthLuaPlugin p, ScriptContext ctx, List<LuaAction?> children, List<Table> tables) : base(p, ctx)
{
_children = children;
_tables = tables;
}
public override string Kind => "RunAllOrdered";
protected override int DefaultTimeoutMs => 0;
protected override int DefaultMaxRetryCount => 0;
protected override bool NeedsLogin => false;
protected override void DescribeFields(Table t)
{
var list = new Table(t.OwnerScript);
for (int i = 0; i < _tables.Count; i++) list.Set(i + 1, DynValue.NewTable(_tables[i]));
t.Set("Actions", DynValue.NewTable(list));
}
protected override bool Send(long now) => true;
protected override void Poll(long now)
{
while (_index < _children.Count)
{
LuaAction? child = _children[_index];
if (child == null)
{
// An action that had already finished when the list was made.
DynValue ok = _tables[_index].RawGet("Success") ?? DynValue.False;
if (!ok.CastToBool())
{
string err = _tables[_index].RawGet("Error")?.CastToString() ?? ActionErrors.PreconditionFailed;
FailAt(err, "an action in the list had already failed");
return;
}
_index++;
continue;
}
if (child.Phase != ActionPhase.Finished)
{
if (child.Owner != this) return; // running in the queue: wait for it
child.Step(now);
if (child.Phase != ActionPhase.Finished) return;
}
if (!child.Success) { FailAt(child.Error, child.ErrorDetails); return; }
_index++;
}
Result = DynValue.NewTable(ResultList());
Succeed(Result);
}
private Table ResultList()
{
var list = new Table(T.OwnerScript);
for (int i = 0; i < _tables.Count; i++) list.Set(i + 1, DynValue.NewTable(_tables[i]));
return list;
}
private void FailAt(string error, string details)
=> Fail(error, $"step {_index + 1} of {_children.Count}: {details}");
public override void HandleChat(string text, ChatHint hint, string error, bool spellOnly, bool coded)
{
if (Phase != ActionPhase.Sent || _index >= _children.Count) return;
LuaAction? child = _children[_index];
if (child != null && child.Owner == this) child.HandleChat(text, hint, error, spellOnly, coded);
}
protected override void Complete(bool success, string error, string details, DynValue result)
{
base.Complete(success, error, details, result);
foreach (LuaAction? c in _children)
if (c != null && c.Owner == this && c.Phase != ActionPhase.Finished) c.Cancel("RunAllOrdered stopped");
}
}

View file

@ -0,0 +1,485 @@
using System;
using System.Collections.Generic;
using MoonSharp.Interpreter;
using RynthCore.PluginSdk;
using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthLua;
// UtilityBelt's other game.Actions: Blank, SetAutorun, SendTellById, CastEquippedWandSpell,
// salvage (SalvageAdd, Salvage), vendor lists (VendorAddToBuyList ... VendorSellAll), trade
// (TradeAdd, TradeAccept, TradeDecline, TradeReset, TradeEnd), and the ones the engine can't
// do yet (UnsupportedAction: they fail with a clear ErrorDetails instead of being missing).
internal static class UbActionErrors
{
public const string NoActions = "NoActions";
public const string NoUst = "NoUst";
public const string UnsalvageableItem = "UnsalvageableItem";
public const string NoTradePartner = "NoTradePartner";
public const string VendorNotOpen = "VendorNotOpen";
public const string VendorDoesntHaveThisItem = "VendorDoesntHaveThisItem";
public const string VendorDoesntHaveEnoughOfThisItem = "VendorDoesntHaveEnoughOfThisItem";
}
/// <summary>Blank(): does nothing and succeeds (a placeholder, e.g. in RunAllOrdered).</summary>
internal sealed class BlankAction : LuaAction
{
public BlankAction(RynthLuaPlugin p, ScriptContext ctx) : base(p, ctx) { }
public override string Kind => "Blank";
protected override bool NeedsLogin => false;
protected override bool Send(long now) { Succeed(); return false; }
}
/// <summary>SetAutorun(enabled): turns autorun on or off.</summary>
internal sealed class AutorunAction : LuaAction
{
public readonly bool Enabled;
public AutorunAction(RynthLuaPlugin p, ScriptContext ctx, bool enabled) : base(p, ctx) => Enabled = enabled;
public override string Kind => "SetAutorun";
protected override int DefaultPriority => ActionPriority.Navigation;
protected override void DescribeFields(Table t) => t.Set("Enabled", DynValue.NewBoolean(Enabled));
protected override bool Send(long now)
{
if (Host.HasSetAutoRun && Host.SetAutoRun(Enabled)) { Succeed(); return false; }
Fail(ActionErrors.Exception, "the engine didn't accept the autorun change");
return false;
}
}
/// <summary>SendTellById(id, message): a tell to that object, by its name ("/t Name, message").</summary>
internal sealed class TellAction : LuaAction
{
public readonly uint ObjectId;
public readonly string Message;
public TellAction(RynthLuaPlugin p, ScriptContext ctx, uint objectId, string message) : base(p, ctx)
{
ObjectId = objectId;
Message = message;
}
public override string Kind => "SendTellById";
public override bool Immediate => true;
protected override int DefaultMaxRetryCount => 0;
protected override void DescribeFields(Table t)
{
t.Set("ObjectId", DynValue.NewNumber(ObjectId));
t.Set("Message", DynValue.NewString(Message));
}
protected override string? Check(out string details)
{
details = string.Empty;
if (!Host.TryGetObjectName(ObjectId, out string name) || name.Length == 0)
{
details = $"no one with id {Hex(ObjectId)}";
return ActionErrors.InvalidTargetObject;
}
return null;
}
protected override bool Send(long now)
{
Host.TryGetObjectName(ObjectId, out string name);
if (Host.HasInvokeChatParser && Host.InvokeChatParser($"/t {name}, {Message}")) { Succeed(DynValue.True); return false; }
Fail(ActionErrors.Exception, "the chat parser didn't take the tell");
return false;
}
}
/// <summary>
/// CastEquippedWandSpell([target]): casts the spell of the wand, staff or orb you wield (AC's
/// "use the equipped caster on the target"). Done on the server's UseDone.
/// </summary>
internal sealed class WandCastAction : LuaAction
{
public readonly uint TargetId;
private uint _wand;
public WandCastAction(RynthLuaPlugin p, ScriptContext ctx, uint targetId) : base(p, ctx) => TargetId = targetId;
public override string Kind => "CastEquippedWandSpell";
protected override int DefaultPriority => ActionPriority.CastSpell;
protected override bool NeedsIdle => true;
protected override bool WatchesServerCodes => true;
protected override void DescribeFields(Table t) => t.Set("TargetId", DynValue.NewNumber(TargetId));
protected override string? Check(out string details)
{
details = string.Empty;
_wand = P.WieldedCaster();
if (_wand == 0) { details = "you aren't wielding a wand, staff or orb"; return ActionErrors.InvalidSourceObject; }
if (TargetId != 0 && !Exists(TargetId)) { details = $"no target {Hex(TargetId)}"; return ActionErrors.InvalidTargetObject; }
return null;
}
protected override bool Send(long now)
{
if (_wand == 0) _wand = P.WieldedCaster();
if (Host.HasUseEquippedItem && Host.UseEquippedItem(_wand, TargetId)) return true;
Fail(ActionErrors.Exception, "the engine didn't accept the wand use");
return false;
}
protected override bool IsMyRefusal(uint eventType, uint code, uint objectId)
=> eventType != 0x00A0 && (code == 0x001D || (WeenieErrors.TryKind(code, out var k) && k == WeenieErrors.Kind.Spell));
protected override void Poll(long now)
{
if (ServerCodes && !Settling && NextUseDone(out uint err))
{
if (err != 0) FailWithCode(err, "the server's UseDone");
else SucceedAfter(now, 100);
}
else if (!ServerCodes && now - SentAt >= 1000 && Host.GetCastBusyState() == 0) SucceedAfter(now, 100);
}
}
// ── Salvage ─────────────────────────────────────────────────────────────────
/// <summary>
/// SalvageAdd(item): puts one of your items in the salvage panel, opening the panel with an
/// Ust from your inventory first when it isn't open (as RynthAi's salvager does).
/// </summary>
internal sealed class SalvageAddAction : ObjectAction
{
private long _nextTry;
private int _tries;
public SalvageAddAction(RynthLuaPlugin p, ScriptContext ctx, uint objectId) : base(p, ctx, objectId, 0) { }
public override string Kind => "SalvageAdd";
protected override int DefaultPriority => ActionPriority.Inventory;
protected override bool NeedsIdle => true;
protected override bool WatchesServerCodes => false;
protected override string? Check(out string details)
{
string? e = NeedObject(out details) ?? NeedMine(out details);
if (e != null) return e;
if (!Host.HasSalvagePanel) { details = "this engine has no salvage panel functions"; return ActionErrors.Exception; }
return null;
}
protected override bool Send(long now)
{
if (TryAdd()) return false;
uint ust = P.FindUst();
if (ust == 0) { Fail(UbActionErrors.NoUst, "no Ust in your inventory"); return false; }
if (!Host.UseFor(ust, "Script", $"{Ctx?.Name ?? "?"}: SalvageAdd opens the salvage panel (UST)", UseKind.Asked)) { Fail(ActionErrors.Exception, "the engine didn't open the salvage panel"); return false; }
_nextTry = now + 400; // the panel animates open first
return true;
}
private bool TryAdd()
{
if (!Host.SalvagePanelAddItem(ObjectId)) return false;
P.SalvageAdded.Add(ObjectId);
Succeed();
return true;
}
protected override void Poll(long now)
{
if (now < _nextTry) return;
if (TryAdd()) return;
_nextTry = now + 200;
if (++_tries >= 15) Fail(ActionErrors.Exception, "the salvage panel didn't take the item (is it open?)");
}
}
/// <summary>Salvage(): salvages what SalvageAdd put in the panel; done when those items are gone.</summary>
internal sealed class SalvageAction : LuaAction
{
private uint[] _items = Array.Empty<uint>();
public SalvageAction(RynthLuaPlugin p, ScriptContext ctx) : base(p, ctx) { }
public override string Kind => "Salvage";
protected override int DefaultPriority => ActionPriority.Inventory;
protected override bool NeedsIdle => true;
protected override int DefaultTimeoutMs => 10000;
protected override int DefaultMaxRetryCount => 0;
protected override string? Check(out string details)
{
details = string.Empty;
P.SalvageAdded.RemoveAll(id => !Exists(id));
if (P.SalvageAdded.Count == 0) { details = "nothing is in the salvage panel (SalvageAdd first)"; return UbActionErrors.NoActions; }
return null;
}
protected override bool Send(long now)
{
_items = P.SalvageAdded.ToArray();
if (!Host.SalvagePanelExecute()) { Fail(ActionErrors.Exception, "the salvage panel didn't salvage"); return false; }
P.SalvageAdded.Clear();
return true;
}
protected override void Poll(long now)
{
foreach (uint id in _items) if (Exists(id)) return;
SucceedAfter(now, 150);
}
}
// ── Vendor ──────────────────────────────────────────────────────────────────
/// <summary>
/// VendorAddToBuyList / VendorAddToSellList / VendorClearBuyList / VendorClearSellList: the
/// buy and sell lists (one per client, like UB's). They change the lists at once.
/// </summary>
internal sealed class VendorListAction : LuaAction
{
public enum Op { AddBuy, AddSell, ClearBuy, ClearSell }
private readonly Op _op;
public readonly uint ObjectId;
public readonly int Amount;
public VendorListAction(RynthLuaPlugin p, ScriptContext ctx, Op op, uint objectId, int amount) : base(p, ctx)
{
_op = op;
ObjectId = objectId;
Amount = amount;
}
public override string Kind => _op switch
{
Op.AddBuy => "VendorAddToBuyList",
Op.AddSell => "VendorAddToSellList",
Op.ClearBuy => "VendorClearBuyList",
_ => "VendorClearSellList",
};
public override bool Immediate => true;
protected override int DefaultMaxRetryCount => 0;
protected override int DefaultPriority => ActionPriority.Vendor;
protected override void DescribeFields(Table t)
{
if (_op is Op.AddBuy or Op.AddSell) t.Set("ObjectId", DynValue.NewNumber(ObjectId));
if (_op == Op.AddBuy) t.Set("Amount", DynValue.NewNumber(Amount));
}
protected override string? Check(out string details)
{
details = string.Empty;
if (_op is Op.ClearBuy or Op.ClearSell) return null;
if (!Host.TryGetVendorInfo(out _)) { details = "no vendor is open"; return UbActionErrors.VendorNotOpen; }
if (_op == Op.AddBuy)
{
if (Amount < 1) { details = "buy at least 1"; return ActionErrors.InvalidInventoryLocation; }
foreach (VendorItem item in Host.GetVendorItems())
{
if (item.ObjectId != ObjectId) continue;
if (!item.Unlimited && item.Amount >= 0 && Amount > item.Amount)
{
details = $"the vendor has {item.Amount}, not {Amount}";
return UbActionErrors.VendorDoesntHaveEnoughOfThisItem;
}
return null;
}
details = $"the vendor doesn't sell {Hex(ObjectId)}";
return UbActionErrors.VendorDoesntHaveThisItem;
}
if (!IsMine(ObjectId)) { details = $"{Describe(ObjectId)} isn't in your inventory"; return ActionErrors.SourceItemNotInInventory; }
return null;
}
protected override bool Send(long now)
{
switch (_op)
{
case Op.AddBuy: P.Cart.AddBuy(ObjectId, Amount); break;
case Op.AddSell: P.Cart.AddSell(ObjectId); break;
case Op.ClearBuy: P.Cart.ClearBuy(); break;
default: P.Cart.ClearSell(); break;
}
Succeed();
return false;
}
}
/// <summary>
/// VendorBuyAll / VendorSellAll: sends the buy or sell list to the open vendor as one
/// transaction; done when the engine reports the server accepted it.
/// </summary>
internal sealed class VendorTradeAction : LuaAction
{
private readonly bool _buy;
private uint _request;
public VendorTradeAction(RynthLuaPlugin p, ScriptContext ctx, bool buy) : base(p, ctx) => _buy = buy;
public override string Kind => _buy ? "VendorBuyAll" : "VendorSellAll";
protected override int DefaultPriority => ActionPriority.Vendor;
protected override bool NeedsIdle => true;
protected override int DefaultTimeoutMs => 12000;
protected override int DefaultMaxRetryCount => 0;
protected override string? Check(out string details)
{
details = string.Empty;
if (!Host.HasVendorTrade || !Host.TryGetVendorInfo(out _)) { details = "no vendor is open"; return UbActionErrors.VendorNotOpen; }
if ((_buy ? P.Cart.BuyList.Count : P.Cart.SellList.Count) == 0)
{
details = $"the {(_buy ? "buy" : "sell")} list is empty";
return UbActionErrors.NoActions;
}
return null;
}
protected override bool Send(long now)
{
_request = _buy ? P.Cart.BuyAll(Host) : P.Cart.SellAll(Host);
if (_request != 0) return true;
string why = Host.TryGetVendorTradeStatus(out VendorTradeStatus st) && st.Message.Length > 0 ? st.Message : "the engine refused the transaction";
Fail(ActionErrors.ServerError, why);
return false;
}
protected override void Poll(long now)
{
if (!Host.TryGetVendorTradeStatus(out VendorTradeStatus st) || st.RequestId != _request || !st.IsFinished) return;
if (st.Succeeded) Succeed();
else Fail(ActionErrors.ServerError, st.Message.Length > 0 ? st.Message : $"the vendor said no ({st.State}, {st.Result})");
}
}
// ── Trade ───────────────────────────────────────────────────────────────────
/// <summary>TradeAdd / TradeAccept / TradeDecline / TradeReset / TradeEnd on the open trade window.</summary>
internal sealed class TradeAction : LuaAction
{
public enum Op { Add, Accept, Decline, Reset, End }
private readonly Op _op;
public readonly uint ObjectId;
private uint _seq, _failures;
public TradeAction(RynthLuaPlugin p, ScriptContext ctx, Op op, uint objectId = 0) : base(p, ctx)
{
_op = op;
ObjectId = objectId;
}
public override string Kind => "Trade" + (_op == Op.Add ? "Add" : _op.ToString());
protected override int DefaultPriority => ActionPriority.Trade;
protected override int DefaultMaxRetryCount => 0;
protected override void DescribeFields(Table t)
{
if (_op == Op.Add) t.Set("ObjectId", DynValue.NewNumber(ObjectId));
}
protected override string? Check(out string details)
{
details = string.Empty;
if (!Host.HasTrade) { details = "this engine has no trade functions"; return ActionErrors.Exception; }
if (!Host.TryGetTradeState(out TradeState st) || !st.IsOpen) { details = "no trade is open"; return UbActionErrors.NoTradePartner; }
if (_op == Op.Add && !IsMine(ObjectId)) { details = $"{Describe(ObjectId)} isn't in your inventory"; return ActionErrors.SourceItemNotInInventory; }
return null;
}
protected override bool Send(long now)
{
Host.TryGetTradeState(out TradeState st);
_seq = st.Sequence;
_failures = st.FailureCount;
bool ok = _op switch
{
Op.Add => Host.TradeAdd(ObjectId),
Op.Accept => Host.TradeAccept(),
Op.Decline => Host.TradeDecline(),
Op.Reset => Host.TradeReset(),
_ => Host.TradeClose(),
};
if (ok) return true;
Fail(ActionErrors.Exception, "the engine didn't accept the trade action");
return false;
}
protected override void Poll(long now)
{
if (!Host.TryGetTradeState(out TradeState st)) return;
switch (_op)
{
case Op.Add:
if (st.FailureCount != _failures && st.LastFailureItemId == ObjectId)
{ FailWithCode(st.LastFailureReason, "the trade refused the item"); return; }
if (Array.IndexOf(Host.GetTradeItems(TradeSide.You), ObjectId) >= 0) Succeed();
break;
case Op.Accept:
if (st.YouAccepted || !st.IsOpen) Succeed();
break;
case Op.Decline:
if (!st.YouAccepted && st.Sequence != _seq) Succeed();
break;
case Op.Reset:
if (st.Sequence != _seq && st.YourItemCount == 0) Succeed();
break;
default:
if (!st.IsOpen) Succeed();
break;
}
}
}
// ── Not available yet ───────────────────────────────────────────────────────
/// <summary>
/// UB actions the engine can't do yet (login/logout, raising skills and attributes, the
/// fellowship, allegiance, inscribing): the call works and the action fails at once with
/// Error "Exception" and an ErrorDetails that says so, instead of the function being missing.
/// </summary>
internal sealed class UnsupportedAction : LuaAction
{
private readonly string _kind;
private readonly string _why;
public UnsupportedAction(RynthLuaPlugin p, ScriptContext ctx, string kind, string why) : base(p, ctx)
{
_kind = kind;
_why = why;
}
public override string Kind => _kind;
protected override bool NeedsLogin => false;
protected override int DefaultMaxRetryCount => 0;
protected override bool Send(long now)
{
Fail(ActionErrors.Exception, $"{_kind} isn't available in RynthLua yet: it needs engine support ({_why})");
return false;
}
}
public sealed partial class RynthLuaPlugin
{
/// <summary>The client's vendor buy/sell lists (UB keeps one per client too); cleared when the vendor closes.</summary>
internal readonly VendorCart Cart = new();
/// <summary>Items SalvageAdd put in the salvage panel, for Salvage.</summary>
internal readonly List<uint> SalvageAdded = new();
/// <summary>A wand, staff or orb the player wields (0: none).</summary>
internal uint WieldedCaster()
{
foreach (uint id in WorldWieldedIds(Host.GetPlayerId()))
if (Host.TryGetItemType(id, out uint t) && (t & ItemTypeCaster) != 0) return id;
return 0;
}
/// <summary>An Ust in the player's inventory (0: none).</summary>
internal uint FindUst()
{
foreach (uint id in WorldInventoryIds())
if (WorldClassOf(id) == OcUst) return id;
return 0;
}
}

View file

@ -0,0 +1,607 @@
using System;
using System.Collections.Generic;
using System.Linq;
using MoonSharp.Interpreter;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthLua;
/// <summary>
/// game.Actions and game.ActionQueue: UtilityBelt's action queue. AC does one use / cast /
/// move at a time, so scripts queue actions and <c>await</c> them:
///
/// local a = await(game.Actions.ObjectUse(potion.Id))
/// if not a.Success then print(a.Error, a.ErrorDetails) end
///
/// One queue for every script (plugin-wide), highest priority first, one action running at
/// a time; Sleep and InvokeChat run beside it. An action's Lua object is a plain table whose
/// fields are rewritten as it runs (see <see cref="LuaAction"/>). A script's actions are
/// cancelled when it stops, everything is cancelled on logout.
///
/// Every call is <c>Kind(args... [, options] [, callback])</c>: the options table
/// (<c>{ Priority, TimeoutMilliseconds, MaxRetryCount, SkipChecks, Name }</c>) and the callback
/// (called with the action when it finishes, as its own coroutine) may come in any order after
/// the arguments. Objects can be passed as WorldObjects or ids.
/// </summary>
public sealed partial class RynthLuaPlugin
{
/// <summary>The SDK host for the action classes (RynthPluginBase.Host is protected).</summary>
internal RynthCoreHost ActHost => Host;
private readonly List<LuaAction> _queuedActions = new();
private readonly List<LuaAction> _immediateActions = new();
private LuaAction? _currentAction;
/// <summary>Unfinished actions by their Lua table (Contains/Remove/RunAllOrdered look them up).</summary>
private readonly Dictionary<Table, LuaAction> _actionsByTable = new(ReferenceEqualityComparer.Instance);
private const string MakeAwaitKey = "rynth_actions_makeawait";
// ── Registration ────────────────────────────────────────────────────────
partial void RegisterActionsApi(Script s, ScriptContext ctx, Table game)
{
var actions = new Table(s);
void Fn(string name, string kind) =>
actions[name] = DynValue.NewCallback((c, a) => CreateAction(s, ctx, kind, LuaArgs.Of(a, actions)));
Fn("ObjectUse", "ObjectUse");
Fn("ObjectUseOn", "ObjectUseOn");
Fn("ObjectApply", "ObjectUseOn"); // UB's name for use-on
Fn("ObjectGive", "ObjectGive");
Fn("ObjectMove", "ObjectMove");
Fn("ObjectSplit", "ObjectSplit");
Fn("ObjectDrop", "ObjectDrop");
Fn("ObjectWield", "ObjectWield");
Fn("ObjectSelect", "ObjectSelect");
Fn("ObjectAppraise", "ObjectAppraise");
Fn("CastSpell", "CastSpell");
Fn("SetCombatMode", "SetCombatMode");
Fn("InvokeChat", "InvokeChat");
Fn("Sleep", "Sleep");
// UtilityBelt's others (GameActionTypesUb.cs).
foreach (string kind in new[]
{
"Blank", "SetAutorun", "SendTellById", "CastEquippedWandSpell", "SalvageAdd", "Salvage",
"VendorAddToBuyList", "VendorAddToSellList", "VendorClearBuyList", "VendorClearSellList",
"VendorBuyAll", "VendorSellAll", "TradeAdd", "TradeAccept", "TradeDecline", "TradeReset", "TradeEnd",
})
Fn(kind, kind);
foreach (string kind in UnsupportedActions.Keys) Fn(kind, kind);
actions["RunAllOrdered"] = DynValue.NewCallback((c, a) => CreateRunAllOrdered(s, ctx, LuaArgs.Of(a, actions)));
var mt = new Table(s);
mt["__tostring"] = DynValue.NewCallback((c, a) => DynValue.NewString("game.Actions"));
actions.MetaTable = mt;
game["Actions"] = DynValue.NewTable(actions);
game["ActionQueue"] = CreateQueueTable(s, ctx);
// UB scripts compare against ActionError.X / pass ActionType.X as a priority.
if (s.Globals.Get("ActionError").IsNil())
{
var errors = new Table(s);
foreach (string e in ActionErrors.All) errors[e] = e;
s.Globals["ActionError"] = DynValue.NewTable(errors);
}
if (s.Globals.Get("ActionType").IsNil())
{
var types = new Table(s);
foreach (var (n, v) in ActionPriority.All) types[n] = (double)v;
s.Globals["ActionType"] = DynValue.NewTable(types);
}
// UB's ActionOptions type: ActionOptions.new() / ActionOptions() give an options table
// (Name, Priority, SkipChecks, MaxRetryCount, TimeoutMilliseconds) to fill in.
if (s.Globals.Get("ActionOptions").IsNil())
{
var ao = new Table(s);
DynValue make = DynValue.NewCallback((c, a) =>
{
var o = new Table(s);
o["SkipChecks"] = false;
return DynValue.NewTable(o);
});
ao["new"] = make;
ao["__new"] = make;
var aoMeta = new Table(s);
aoMeta["__call"] = DynValue.NewCallback((c, a) => make.Callback.ClrCallback(c, a));
aoMeta["__tostring"] = DynValue.NewCallback((c, a) => DynValue.NewString("ActionOptions"));
ao.MetaTable = aoMeta;
s.Globals["ActionOptions"] = DynValue.NewTable(ao);
}
ctx.OnStop.Add(() => CancelActionsOf(ctx, "the script stopped"));
// A script whose main code ends with actions still queued keeps running until they finish
// (so their callbacks run).
ctx.KeepAlive.Add(() =>
{
int n = 0;
foreach (LuaAction a in _queuedActions) if (a.Ctx == ctx && a.Phase != ActionPhase.Finished) n++;
foreach (LuaAction a in _immediateActions) if (a.Ctx == ctx && a.Phase != ActionPhase.Finished) n++;
return n;
});
}
/// <summary>WorldObject action methods (raw fields): Use, UseOn, Give, Move, Split, Drop, Select, Appraise, Wield.</summary>
partial void DecorateObjectActions(Script s, ScriptContext ctx, uint id, Table obj)
{
DynValue idv = DynValue.NewNumber(id);
DynValue[] With(DynValue[] rest)
{
var r = new DynValue[rest.Length + 1];
r[0] = idv;
Array.Copy(rest, 0, r, 1, rest.Length);
return r;
}
void M(string name, string kind) =>
obj.Set(name, DynValue.NewCallback((c, a) => CreateAction(s, ctx, kind, With(LuaArgs.Of(a, obj)))));
M("Use", "ObjectUse");
M("UseOn", "ObjectUseOn");
M("Give", "ObjectGive");
M("Move", "ObjectMove");
M("Drop", "ObjectDrop");
M("Select", "ObjectSelect");
M("Appraise", "ObjectAppraise");
M("Wield", "ObjectWield");
M("AddToSalvage", "SalvageAdd");
M("AddToTrade", "TradeAdd");
M("Inscribe", "Inscribe");
// Salvage(): UB's RunAllOrdered of SalvageAdd(this) and Salvage().
obj.Set("Salvage", DynValue.NewCallback((c, a) =>
{
SplitArgs(LuaArgs.Of(a, obj), out _, out ActionOptions o, out DynValue cb);
DynValue add = Finish(s, ctx, BuildAction(ctx, "SalvageAdd", new List<DynValue> { idv }), default, DynValue.Nil);
DynValue run = Finish(s, ctx, BuildAction(ctx, "Salvage", new List<DynValue>()), default, DynValue.Nil);
var list = new Table(s);
list.Set(1, add);
list.Set(2, run);
return CreateRunAllOrderedWith(s, ctx, list, o, cb);
}));
// Split(amount [, container [, slot]]) → ObjectSplit(id, container, amount, slot)
obj.Set("Split", DynValue.NewCallback((c, a) =>
{
SplitArgs(LuaArgs.Of(a, obj), out var pos, out ActionOptions o, out DynValue cb);
var p = new List<DynValue> { idv, Pos(pos, 1), Pos(pos, 0), Pos(pos, 2) };
return Finish(s, ctx, BuildAction(ctx, "ObjectSplit", p), o, cb);
}));
}
// ── Creating actions ────────────────────────────────────────────────────
private DynValue CreateAction(Script s, ScriptContext ctx, string kind, DynValue[] args)
{
SplitArgs(args, out var pos, out ActionOptions o, out DynValue cb);
return Finish(s, ctx, BuildAction(ctx, kind, pos), o, cb);
}
private DynValue Finish(Script s, ScriptContext ctx, LuaAction action, ActionOptions o, DynValue cb)
{
action.ApplyOptions(o);
action.Callback = cb;
action.CreateTable(s, MakeAwait(s));
_actionsByTable[action.T] = action;
if (action.Immediate) _immediateActions.Add(action);
else _queuedActions.Add(action);
return DynValue.NewTable(action.T);
}
private LuaAction BuildAction(ScriptContext ctx, string kind, List<DynValue> pos)
{
switch (kind)
{
case "ObjectUse":
return new UseAction(this, ctx, Obj(pos, 0, kind), OptObj(pos, 1), on: false);
case "ObjectUseOn":
return new UseAction(this, ctx, Obj(pos, 0, kind), Obj(pos, 1, kind, "target"), on: true);
case "ObjectGive":
return new GiveAction(this, ctx, Obj(pos, 0, kind), Obj(pos, 1, kind, "target"));
case "ObjectMove":
{
uint id = Obj(pos, 0, kind);
uint container = Obj(pos, 1, kind, "container");
int slot = (int)LuaArgs.Num(Pos(pos, 2), 0);
DynValue st = Pos(pos, 3);
bool stack = st.IsNil() || st.CastToBool();
return new MoveAction(this, ctx, id, container, slot, stack);
}
case "ObjectSplit":
{
// UB: (object, container, newStackSize [, slot]); short form: (object, newStackSize).
uint id = Obj(pos, 0, kind);
uint container;
int amount, slot;
if (pos.Count >= 3)
{
container = OptObj(pos, 1);
amount = (int)LuaArgs.Num(Pos(pos, 2), 0);
slot = (int)LuaArgs.Num(Pos(pos, 3), 0);
}
else
{
container = 0;
amount = (int)LuaArgs.Num(Pos(pos, 1), 0);
slot = 0;
}
if (amount < 1) throw new ScriptRuntimeException("ObjectSplit needs the size of the new stack (1 or more)");
return new SplitAction(this, ctx, id, container, amount, slot);
}
case "ObjectDrop":
return new DropAction(this, ctx, Obj(pos, 0, kind));
case "ObjectWield":
return new WieldAction(this, ctx, Obj(pos, 0, kind), (uint)LuaArgs.Num(Pos(pos, 1), 0));
case "ObjectSelect":
return new SelectAction(this, ctx, Obj(pos, 0, kind));
case "ObjectAppraise":
return new AppraiseAction(this, ctx, Obj(pos, 0, kind));
case "CastSpell":
{
DynValue sp = Pos(pos, 0);
if (sp.Type != DataType.Number && !double.TryParse(sp.CastToString(), out _))
throw new ScriptRuntimeException("CastSpell(spellId [, target]) needs a spell id");
return new CastSpellAction(this, ctx, (int)LuaArgs.Num(sp), OptObj(pos, 1));
}
case "SetCombatMode":
return new CombatModeAction(this, ctx, CombatModeArg(Pos(pos, 0)));
case "InvokeChat":
{
string text = LuaArgs.Str(Pos(pos, 0)).Trim();
if (text.Length == 0) throw new ScriptRuntimeException("InvokeChat(text) needs some text");
return new InvokeChatAction(this, ctx, text);
}
case "Sleep":
{
DynValue ms = Pos(pos, 0);
if (ms.Type != DataType.Number) throw new ScriptRuntimeException("Sleep(milliseconds) needs a number");
return new SleepAction(this, ctx, (int)Math.Min(int.MaxValue, Math.Max(0, ms.Number)));
}
case "Blank":
return new BlankAction(this, ctx);
case "SetAutorun":
return new AutorunAction(this, ctx, Pos(pos, 0).CastToBool());
case "SendTellById":
{
uint id = Obj(pos, 0, kind, "player");
string text = LuaArgs.Str(Pos(pos, 1)).Trim();
if (text.Length == 0) throw new ScriptRuntimeException("SendTellById(id, message) needs a message");
return new TellAction(this, ctx, id, text);
}
case "CastEquippedWandSpell":
return new WandCastAction(this, ctx, OptObj(pos, 0));
case "SalvageAdd":
return new SalvageAddAction(this, ctx, Obj(pos, 0, kind));
case "Salvage":
return new SalvageAction(this, ctx);
case "VendorAddToBuyList":
{
DynValue amt = Pos(pos, 1);
return new VendorListAction(this, ctx, VendorListAction.Op.AddBuy, Obj(pos, 0, kind), amt.IsNil() ? 1 : (int)LuaArgs.Num(amt, 1));
}
case "VendorAddToSellList":
return new VendorListAction(this, ctx, VendorListAction.Op.AddSell, Obj(pos, 0, kind), 0);
case "VendorClearBuyList":
return new VendorListAction(this, ctx, VendorListAction.Op.ClearBuy, 0, 0);
case "VendorClearSellList":
return new VendorListAction(this, ctx, VendorListAction.Op.ClearSell, 0, 0);
case "VendorBuyAll":
return new VendorTradeAction(this, ctx, buy: true);
case "VendorSellAll":
return new VendorTradeAction(this, ctx, buy: false);
case "TradeAdd":
return new TradeAction(this, ctx, TradeAction.Op.Add, Obj(pos, 0, kind));
case "TradeAccept":
return new TradeAction(this, ctx, TradeAction.Op.Accept);
case "TradeDecline":
return new TradeAction(this, ctx, TradeAction.Op.Decline);
case "TradeReset":
return new TradeAction(this, ctx, TradeAction.Op.Reset);
case "TradeEnd":
return new TradeAction(this, ctx, TradeAction.Op.End);
}
if (UnsupportedActions.TryGetValue(kind, out string? why))
return new UnsupportedAction(this, ctx, kind, why);
throw new ScriptRuntimeException($"unknown action {kind}");
}
/// <summary>UB actions the engine can't do yet, and why (they fail with that reason).</summary>
private static readonly Dictionary<string, string> UnsupportedActions = new()
{
["Login"] = "no host function logs a character in",
["Logout"] = "no host function logs out",
["SkillAdvance"] = "no host function trains a skill",
["AttributeAddExperience"] = "no host function spends experience",
["SkillAddExperience"] = "no host function spends experience",
["VitalAddExperience"] = "no host function spends experience",
["FellowCreate"] = "no host functions for the fellowship",
["FellowDisband"] = "no host functions for the fellowship",
["FellowDismiss"] = "no host functions for the fellowship",
["FellowSetLeader"] = "no host functions for the fellowship",
["FellowQuit"] = "no host functions for the fellowship",
["FellowRecruit"] = "no host functions for the fellowship",
["FellowSetOpen"] = "no host functions for the fellowship",
["AllegianceSwear"] = "no host functions for the allegiance",
["AllegianceBreak"] = "no host functions for the allegiance",
["Inscribe"] = "no host function inscribes an item",
};
private DynValue CreateRunAllOrdered(Script s, ScriptContext ctx, DynValue[] args)
{
DynValue listArg = args.Length > 0 ? args[0] : DynValue.Nil;
if (listArg.Type != DataType.Table)
throw new ScriptRuntimeException("RunAllOrdered({ action, action, ... } [, options] [, callback]) needs a list of actions");
SplitArgs(args.Skip(1).ToArray(), out _, out ActionOptions o, out DynValue cb);
return CreateRunAllOrderedWith(s, ctx, listArg.Table, o, cb);
}
private DynValue CreateRunAllOrderedWith(Script s, ScriptContext ctx, Table list, ActionOptions o, DynValue cb)
{
var children = new List<LuaAction?>();
var tables = new List<Table>();
for (int i = 1; i <= list.Length; i++)
{
DynValue v = list.Get(i);
if (v.Type != DataType.Table || v.Table.RawGet("__rynth_action") == null)
throw new ScriptRuntimeException($"RunAllOrdered: item {i} isn't an action (make them with game.Actions...)");
Table t = v.Table;
_actionsByTable.TryGetValue(t, out LuaAction? child);
if (child != null && child.Ctx != ctx)
throw new ScriptRuntimeException($"RunAllOrdered: item {i} belongs to another script");
if (child != null && child.Owner != null)
throw new ScriptRuntimeException($"RunAllOrdered: item {i} is already in another RunAllOrdered");
children.Add(child);
tables.Add(t);
}
var run = new RunAllOrderedAction(this, ctx, children, tables);
// Take the actions that haven't started out of the queue: the list runs them.
foreach (LuaAction? c in children)
{
if (c == null || c.Phase != ActionPhase.Queued) continue;
_queuedActions.Remove(c);
_immediateActions.Remove(c);
c.Owner = run;
}
return Finish(s, ctx, run, o, cb);
}
/// <summary>A per-script Lua factory for the actions' Await() closures.</summary>
private static DynValue MakeAwait(Script s)
{
DynValue f = s.Registry.Get(MakeAwaitKey);
if (f.Type == DataType.Function) return f;
try
{
f = s.DoString("return function(a) return function() return await(a) end end", null, "rynth-actions");
s.Registry.Set(MakeAwaitKey, f);
}
catch { f = DynValue.Nil; }
return f;
}
// ── Argument helpers ────────────────────────────────────────────────────
/// <summary>Positional arguments, then an options table and a callback in either order.</summary>
private static void SplitArgs(DynValue[] args, out List<DynValue> pos, out ActionOptions options, out DynValue callback)
{
pos = new List<DynValue>();
options = default;
callback = DynValue.Nil;
foreach (DynValue v in args)
{
if (v.Type == DataType.Function) { callback = v; continue; }
if (v.Type == DataType.ClrFunction) throw new ScriptRuntimeException("the action callback must be a Lua function");
if (v.Type == DataType.Table && !IsObjectTable(v.Table) && !LuaEnumValues.IsTyped(v)) { options = ParseOptions(v.Table); continue; }
pos.Add(v);
}
// Trailing nils (e.g. f(id, nil, callback)) are just missing arguments.
while (pos.Count > 0 && pos[^1].IsNil()) pos.RemoveAt(pos.Count - 1);
}
private static bool IsObjectTable(Table t) =>
t.RawGet("__rynth_object") != null || t.RawGet("Id")?.Type == DataType.Number;
private static ActionOptions ParseOptions(Table t)
{
var o = new ActionOptions();
DynValue p = t.Get("Priority");
if (p.Type == DataType.Number) o.Priority = (int)Math.Clamp(p.Number, int.MinValue, int.MaxValue);
else if (p.Type == DataType.String)
{
if (!ActionPriority.TryParse(p.String, out int pv))
throw new ScriptRuntimeException($"Priority \"{p.String}\": use a number or an ActionType name (Wield, CastSpell, Inventory, Misc, ...)");
o.Priority = pv;
}
DynValue to = t.Get("TimeoutMilliseconds");
if (to.Type == DataType.Number) o.TimeoutMs = (int)Math.Clamp(to.Number, 0, int.MaxValue);
DynValue r = t.Get("MaxRetryCount");
if (r.Type == DataType.Number) o.MaxRetryCount = (int)Math.Clamp(r.Number, 0, 1000);
o.SkipChecks = t.Get("SkipChecks").CastToBool();
DynValue n = t.Get("Name");
if (n.Type == DataType.String && n.String.Length > 0) o.Name = n.String;
return o;
}
private static DynValue Pos(List<DynValue> pos, int i) => i < pos.Count ? pos[i] : DynValue.Nil;
private static uint Obj(List<DynValue> pos, int i, string fn, string what = "object")
{
uint id = LuaArgs.Id(Pos(pos, i));
if (id == 0) throw new ScriptRuntimeException($"{fn} needs {(what == "object" ? "an object" : "a " + what)} (a WorldObject or an id)");
return id;
}
private static uint OptObj(List<DynValue> pos, int i) => LuaArgs.Id(Pos(pos, i));
private static int CombatModeArg(DynValue v)
{
if (v.Type == DataType.Number)
{
int m = (int)v.Number;
if (m is 1 or 2 or 4 or 8) return m;
}
else if (v.Type == DataType.String && LuaEnums.CombatMode.TryGetValue(v.String.Trim(), out int named))
return named;
throw new ScriptRuntimeException("SetCombatMode(mode) needs CombatMode.NonCombat/Melee/Missile/Magic (1, 2, 4, 8) or its name");
}
// ── The queue ───────────────────────────────────────────────────────────
partial void ActionsTick()
{
if (_currentAction == null && _queuedActions.Count == 0 && _immediateActions.Count == 0) return;
long now = Environment.TickCount64;
if (_immediateActions.Count > 0)
{
foreach (LuaAction a in _immediateActions.ToArray())
if (a.Owner == null) StepAction(a, now);
_immediateActions.RemoveAll(a => a.Phase == ActionPhase.Finished || a.Owner != null);
}
if (_currentAction != null && _currentAction.Phase == ActionPhase.Finished) _currentAction = null;
_queuedActions.RemoveAll(a => a.Phase == ActionPhase.Finished || a.Owner != null);
if (_currentAction == null && _queuedActions.Count > 0)
{
// Highest priority first; the same priority in the order queued.
LuaAction best = _queuedActions[0];
foreach (LuaAction a in _queuedActions)
if (a.Priority > best.Priority || (a.Priority == best.Priority && a.ActionId < best.ActionId)) best = a;
_queuedActions.Remove(best);
_currentAction = best;
}
if (_currentAction != null)
{
StepAction(_currentAction, now);
if (_currentAction.Phase == ActionPhase.Finished) _currentAction = null;
}
}
private static void StepAction(LuaAction a, long now)
{
if (!a.Ctx.Host.Loaded) { a.Cancel("the script stopped"); return; }
try { a.Step(now); }
catch (Exception ex) { a.Fail(ActionErrors.Exception, ex.Message); }
}
/// <summary>An action finished (any way): it isn't in the queue anymore.</summary>
internal void OnActionFinished(LuaAction a)
{
if (a.T != null) _actionsByTable.Remove(a.T);
}
partial void ActionsOnChatText(string text, int chatType)
{
LuaAction? a = _currentAction;
if (a == null) return;
string t = text.Trim();
if (t.Length == 0 || ActionChat.IsSpeech(t)) return;
ChatHint hint = ActionChat.Classify(t, out string error, out bool spellOnly, out bool coded);
if (hint == ChatHint.None) return;
try { a.HandleChat(t, hint, error, spellOnly, coded); }
catch (Exception ex) { a.Fail(ActionErrors.Exception, ex.Message); }
}
partial void ActionsOnLogout()
{
foreach (LuaAction a in AllLiveActions()) a.Cancel("logged out");
_queuedActions.Clear();
_immediateActions.Clear();
_currentAction = null;
}
private void CancelActionsOf(ScriptContext ctx, string why)
{
foreach (LuaAction a in AllLiveActions())
if (a.Ctx == ctx) a.Cancel(why);
_queuedActions.RemoveAll(a => a.Phase == ActionPhase.Finished);
_immediateActions.RemoveAll(a => a.Phase == ActionPhase.Finished);
if (_currentAction?.Phase == ActionPhase.Finished) _currentAction = null;
}
/// <summary>Running first, then the queue in run order, then the immediate ones.</summary>
private List<LuaAction> AllLiveActions()
{
var list = new List<LuaAction>();
if (_currentAction != null && _currentAction.Phase != ActionPhase.Finished) list.Add(_currentAction);
list.AddRange(_queuedActions.Where(a => a.Phase != ActionPhase.Finished && a.Owner == null)
.OrderByDescending(a => a.Priority).ThenBy(a => a.ActionId));
list.AddRange(_immediateActions.Where(a => a.Phase != ActionPhase.Finished && a.Owner == null));
return list;
}
// ── game.ActionQueue ────────────────────────────────────────────────────
/// <summary>
/// game.ActionQueue: <c>Queue</c> (running + waiting, in run order), <c>ImmediateQueue</c>,
/// <c>Count</c>, <c>Current</c>, <c>IsBusy</c>; <c>Contains(action)</c>, <c>Add(action)</c>,
/// <c>Remove(action)</c>, <c>Clear()</c>. Another script's action shows as a summary table
/// (Name, ActionType, Priority, ScriptName, IsStarted, IsRunning); Remove and Clear only
/// touch this script's own actions.
/// </summary>
private DynValue CreateQueueTable(Script s, ScriptContext ctx)
{
var q = new Table(s);
LuaAction? Lookup(DynValue v) =>
v.Type == DataType.Table && _actionsByTable.TryGetValue(v.Table, out LuaAction? a) ? a : null;
q["Contains"] = DynValue.NewCallback((c, a) => DynValue.NewBoolean(Lookup(LuaArgs.At(LuaArgs.Of(a, q), 0)) != null));
// Actions are queued when they're made; Add only reports whether this one is (still) queued.
q["Add"] = DynValue.NewCallback((c, a) => DynValue.NewBoolean(Lookup(LuaArgs.At(LuaArgs.Of(a, q), 0)) != null));
q["Remove"] = DynValue.NewCallback((c, a) =>
{
LuaAction? act = Lookup(LuaArgs.At(LuaArgs.Of(a, q), 0));
if (act == null) return DynValue.False;
if (act.Ctx != ctx) throw new ScriptRuntimeException("ActionQueue.Remove: that action belongs to another script");
act.Cancel("removed from the queue");
return DynValue.True;
});
q["Clear"] = DynValue.NewCallback((c, a) =>
{
int n = AllLiveActions().Count(x => x.Ctx == ctx);
CancelActionsOf(ctx, "the queue was cleared");
return DynValue.NewNumber(n);
});
DynValue View(LuaAction a)
{
if (a.Ctx == ctx) return DynValue.NewTable(a.T);
var t = new Table(s);
t["Name"] = a.Name;
t["ActionType"] = (double)a.Category;
t["Kind"] = a.Kind;
t["Priority"] = (double)a.Priority;
t["ScriptName"] = a.Ctx.Name;
t["IsStarted"] = a.Phase != ActionPhase.Queued;
t["IsRunning"] = a.Phase is ActionPhase.Waiting or ActionPhase.Sent or ActionPhase.RetryWait;
t["IsFinished"] = false;
return DynValue.NewTable(t);
}
DynValue ListOf(IEnumerable<LuaAction> actions)
{
var t = new Table(s);
int i = 1;
foreach (LuaAction a in actions) t.Set(i++, View(a));
return DynValue.NewTable(t);
}
var mt = new Table(s);
mt["__index"] = DynValue.NewCallback((c, a) =>
{
string key = a.Count > 1 ? a[1].CastToString() ?? "" : "";
switch (key)
{
case "Queue": return ListOf(AllLiveActions().Where(x => !x.Immediate));
case "ImmediateQueue": return ListOf(AllLiveActions().Where(x => x.Immediate));
case "Count": return DynValue.NewNumber(AllLiveActions().Count);
case "Current": return _currentAction != null && _currentAction.Phase != ActionPhase.Finished ? View(_currentAction) : DynValue.Nil;
case "IsBusy": return DynValue.NewBoolean(_currentAction != null && _currentAction.Phase != ActionPhase.Finished);
default: return DynValue.Nil;
}
});
mt["__tostring"] = DynValue.NewCallback((c, a) =>
DynValue.NewString($"ActionQueue ({AllLiveActions().Count} action(s){(_currentAction != null ? ", running " + _currentAction.Name : "")})"));
q.MetaTable = mt;
return DynValue.NewTable(q);
}
}

View file

@ -0,0 +1,258 @@
using System;
using System.Collections.Concurrent;
using System.Linq;
using MoonSharp.Interpreter;
namespace RynthCore.Plugin.RynthLua;
/// <summary>
/// The v2 API root: the <c>game</c> global (UtilityBelt's shape), script chat commands,
/// the module registry for <c>require</c>, and the hooks each API area implements in its
/// own file (partial methods: an area that isn't built yet simply isn't there).
///
/// World GameWorld*.cs game.World, WorldObject
/// Character GameCharacter*.cs game.Character
/// Actions GameActions*.cs game.Actions, game.ActionQueue, action objects
/// Library Library*.cs require("storage"), "enums" (+ globals), "json", "rynth.ai"
///
/// Everything here runs on the plugin pump thread.
/// </summary>
public sealed partial class RynthLuaPlugin
{
// ── Hooks the API areas implement ───────────────────────────────────────
// World
partial void RegisterWorldApi(Script s, ScriptContext ctx, Table game);
partial void WorldTick();
partial void WorldOnLogin();
partial void WorldOnLogout();
partial void WorldOnCreateObject(uint objectId);
partial void WorldOnDeleteObject(uint objectId);
partial void WorldOnChatText(string text, int chatType);
partial void WorldOnSelected(uint currentId, uint previousId);
partial void WorldOnVendor(uint vendorId, bool open);
// Character
partial void RegisterCharacterApi(Script s, ScriptContext ctx, Table game);
partial void CharacterTick();
partial void CharacterOnLogin();
partial void CharacterOnLogout();
partial void CharacterOnCombatModeChange(int currentMode, int previousMode);
partial void CharacterOnEnchantmentAdded(uint spellId, double durationSeconds);
partial void CharacterOnEnchantmentRemoved(uint enchantmentId);
partial void CharacterOnChatText(string text, int chatType);
partial void CharacterOnUpdateHealth(uint targetId, float ratio, uint current, uint max);
// Actions
partial void RegisterActionsApi(Script s, ScriptContext ctx, Table game);
partial void ActionsTick();
partial void ActionsOnChatText(string text, int chatType);
partial void ActionsOnLogout();
// Library modules and globals
partial void RegisterLibraryGlobals(Script s, ScriptContext ctx);
partial void ResolveLibraryModule(Script s, ScriptContext ctx, string name, ref DynValue? module);
// WorldObject: WrapObject makes the table (raw fields Id and __rynth_object = true);
// World fills in the properties (its __index metatable), Actions adds the action methods.
partial void DecorateObject(Script s, ScriptContext ctx, uint id, Table obj);
partial void DecorateObjectActions(Script s, ScriptContext ctx, uint id, Table obj);
/// <summary>
/// The Lua object for world object <paramref name="id"/> in this script (nil for 0).
/// Every area hands out objects through this, so they all have the same shape:
/// a table with the raw field <c>Id</c> (LuaArgs.Id reads it), properties from World and
/// action methods from Actions.
/// </summary>
internal DynValue WrapObject(Script s, ScriptContext ctx, uint id)
{
if (id == 0) return DynValue.Nil;
var t = new Table(s);
t["Id"] = (double)id;
t["__rynth_object"] = true;
DecorateObject(s, ctx, id, t);
DecorateObjectActions(s, ctx, id, t);
return DynValue.NewTable(t);
}
// ── Game state ──────────────────────────────────────────────────────────
/// <summary>"CharacterSelect", "InGame" or "LoggingOut".</summary>
internal string GameState { get; private set; } = "CharacterSelect";
internal long LastTick { get; private set; }
/// <summary>Script chat commands ("/name" → owning script), readable from AC's thread.</summary>
private readonly ConcurrentDictionary<string, string> _commandOwners = new(StringComparer.OrdinalIgnoreCase);
private readonly ConcurrentQueue<(string Script, string Command, string Args)> _pendingScriptCommands = new();
private void SetGameState(string state)
{
if (GameState == state) return;
GameState = state;
FireAll("Game.OnStateChanged", s =>
{
var t = new Table(s);
t["NewState"] = state;
return DynValue.NewTable(t);
});
}
/// <summary>Fires a v2 event on every running script that listens for it.</summary>
internal void FireAll(string key, Func<Script, DynValue> makeArgs)
{
foreach (var ctx in _scripts.Values.ToArray())
if (ctx.Host.Loaded && ctx.HasHandlers(key)) ctx.Fire(key, makeArgs);
}
/// <summary>
/// game.OnScriptEnd: handlers are called directly (no coroutine), right before the
/// script's state goes away, whether it was stopped from outside or called stop().
/// </summary>
private void FireScriptEnd(ScriptContext ctx)
{
ctx.Host.BeforeScriptStop = null;
ctx.FireNow("Game.OnScriptEnd", s => DynValue.NewTable(new Table(s)));
}
// ── Registration ────────────────────────────────────────────────────────
/// <summary>Every script's globals: v1 (chat, me, meta, RynthAi, ...) and v2 (game, require modules).</summary>
private void RegisterApi(Script s, LuaScriptHost host, ScriptContext ctx)
{
RegisterV1Api(s, host);
host.BeforeScriptStop = () => FireScriptEnd(ctx);
RegisterGame(s, ctx);
RegisterLibraryGlobals(s, ctx);
ExtraGlobals?.Invoke(s, ctx.Name);
}
// ── Seams for the offline test harness (Tools\RynthLua.CompatTests) ─────
// Unused by the plugin itself: ExtraGlobals stays null and nothing calls the readers.
/// <summary>Test harness only: adds globals to every new script state (script name given).</summary>
internal static Action<Script, string>? ExtraGlobals { get; set; }
/// <summary>Test harness only: a script's console text ("" when it never ran).</summary>
internal string ScriptConsoleText(string name) =>
_scripts.TryGetValue(name, out var ctx) ? ctx.Host.ConsoleText() : string.Empty;
/// <summary>Test harness only: whether a script's Lua state is still alive.</summary>
internal bool ScriptIsLoaded(string name) => _scripts.TryGetValue(name, out var ctx) && ctx.Host.Loaded;
private void RegisterGame(Script s, ScriptContext ctx)
{
var game = new Table(s);
game["OnTick"] = ctx.Event("Game.OnTick").CreateTable(s);
game["OnStateChanged"] = ctx.Event("Game.OnStateChanged").CreateTable(s);
game["OnScriptEnd"] = ctx.Event("Game.OnScriptEnd").CreateTable(s);
game["ScriptName"] = ctx.Name;
// UB's Capabilities: Has(ClientCapability.X) / Get(). ImGui (1) when the engine can
// show script windows.
var caps = new Table(s);
int CapsNow() => Host.HasUi ? 1 : 0;
caps["Get"] = DynValue.NewCallback((c, a) => DynValue.NewNumber(CapsNow()));
caps["Has"] = DynValue.NewCallback((c, a) =>
{
long want = (long)LuaArgs.Num(LuaArgs.At(LuaArgs.Of(a, caps), 0), 0);
return DynValue.NewBoolean(want != 0 && (CapsNow() & want) == want);
});
game["Capabilities"] = DynValue.NewTable(caps);
game["RegisterCommand"] = DynValue.NewCallback((c, a) =>
{
var args = LuaArgs.Of(a, game);
string cmd = LuaArgs.Str(LuaArgs.At(args, 0)).Trim();
DynValue fn = LuaArgs.At(args, 1);
if (cmd.Length == 0 || fn.Type != DataType.Function)
throw new ScriptRuntimeException("RegisterCommand(\"/name\", function(args) end) needs a command and a function");
if (!cmd.StartsWith('/')) cmd = "/" + cmd;
if (_commandOwners.TryGetValue(cmd, out string? owner) && !owner.Equals(ctx.Name, StringComparison.OrdinalIgnoreCase))
throw new ScriptRuntimeException($"{cmd} is already a command of script {owner}");
ctx.Commands[cmd] = fn;
_commandOwners[cmd] = ctx.Name;
return DynValue.Nil;
});
game["UnregisterCommand"] = DynValue.NewCallback((c, a) =>
{
string cmd = LuaArgs.Str(LuaArgs.At(LuaArgs.Of(a, game), 0)).Trim();
if (!cmd.StartsWith('/')) cmd = "/" + cmd;
ctx.Commands.Remove(cmd);
if (_commandOwners.TryGetValue(cmd, out string? owner) && owner.Equals(ctx.Name, StringComparison.OrdinalIgnoreCase))
_commandOwners.TryRemove(cmd, out _);
return DynValue.Nil;
});
ctx.OnStop.Add(() =>
{
foreach (var kv in _commandOwners.ToArray())
if (kv.Value.Equals(ctx.Name, StringComparison.OrdinalIgnoreCase)) _commandOwners.TryRemove(kv.Key, out _);
});
var mt = new Table(s);
mt["__index"] = DynValue.NewCallback((c, a) =>
{
string key = a.Count > 1 ? a[1].CastToString() ?? "" : "";
switch (key)
{
case "ServerName": return DynValue.NewString(Host.TryGetWorldName(out string w) ? w : string.Empty);
case "AccountName": return DynValue.NewString(Host.TryGetAccountName(out string acct) ? acct : string.Empty);
case "CharacterId": return DynValue.NewNumber(Host.GetPlayerId());
case "State": return DynValue.NewString(GameState);
case "LastTick": return DynValue.NewNumber(LastTick);
default: return DynValue.Nil;
}
});
mt["__tostring"] = DynValue.NewCallback((c, a) => DynValue.NewString("game"));
game.MetaTable = mt;
RegisterWorldApi(s, ctx, game);
RegisterCharacterApi(s, ctx, game);
RegisterActionsApi(s, ctx, game);
s.Globals["game"] = DynValue.NewTable(game);
}
/// <summary>require(name): library modules first; "rynthlua" is the plugin's own info.</summary>
private DynValue? ResolveModule(Script s, ScriptContext ctx, string name)
{
DynValue? module = null;
ResolveLibraryModule(s, ctx, name, ref module);
return module;
}
// ── Script commands ─────────────────────────────────────────────────────
/// <summary>AC's thread: a line starting with a script's command is eaten and queued.</summary>
private bool TryQueueScriptCommand(string line)
{
if (_commandOwners.IsEmpty) return false;
int sp = line.IndexOf(' ');
string cmd = sp < 0 ? line : line[..sp];
if (!_commandOwners.TryGetValue(cmd, out string? owner)) return false;
_pendingScriptCommands.Enqueue((owner, cmd, sp < 0 ? string.Empty : line[(sp + 1)..].Trim()));
return true;
}
private void RunPendingScriptCommands()
{
while (_pendingScriptCommands.TryDequeue(out var p))
{
if (!_scripts.TryGetValue(p.Script, out var ctx) || !ctx.Host.Loaded) continue;
if (!ctx.Commands.TryGetValue(p.Command, out DynValue? fn)) continue;
ctx.Host.Start(fn, new[] { DynValue.NewString(p.Args) });
}
}
/// <summary>Per tick, before scripts run: areas poll state, game.OnTick fires.</summary>
private void TickApi()
{
LastTick = Environment.TickCount64;
RunPendingScriptCommands();
WorldTick();
WorldTickChatInput();
CharacterTick();
TradeTick();
ActionsTick();
FireAll("Game.OnTick", s => DynValue.NewTable(new Table(s)));
FireAll("World.OnTick", s => DynValue.NewTable(new Table(s)));
}
}

View file

@ -0,0 +1,779 @@
using System;
using System.Collections.Generic;
using MoonSharp.Interpreter;
namespace RynthCore.Plugin.RynthLua;
/// <summary>
/// <c>game.Character</c> (UtilityBelt's shape): who you are, vitals, skills, attributes,
/// burden, combat mode, inventory and equipment, enchantments and the spellbook, plus the
/// character events. Values are read live through the SDK on every access (an
/// <c>__index</c> metatable); events the engine doesn't raise are found by polling in
/// <see cref="CharacterTick"/> (vitals and portal space every tick, the rest every 500 ms and
/// only while a script listens).
///
/// Enum-valued fields are numbers, so they compare with the enum globals the way UB scripts
/// do (<c>game.Character.CombatMode == CombatMode.Melee</c>), with a name twin
/// (<c>CombatModeName</c>, <c>TrainingName</c>, <c>TypeName</c>); arguments take either a
/// number (LuaEnums numbering) or a name. Everything here runs on the plugin pump thread.
/// </summary>
public sealed partial class RynthLuaPlugin
{
// ── AC property ids (STypes) ────────────────────────────────────────────
private const uint ChIntEncumbrance = 5; // EncumbranceVal: burden units carried
private const uint ChIntStackSize = 12;
private const uint ChIntLevel = 25;
private const uint ChIntAugCarrying = 230; // AugmentationIncreasedCarryingCapacity
private const uint ChInt64TotalXp = 1;
private const uint ChInt64UnassignedXp = 2;
private const uint ChInt64AvailableLum = 6;
private const uint ChInt64MaxLum = 7;
private const uint ChItemTypeContainer = 0x200;
private static readonly string[] CharacterEventNames =
{
"OnVitalChanged", "OnPortalSpaceEntered", "OnPortalSpaceExited", "OnDeath",
"OnCombatModeChanged", "OnEnchantmentsChanged", "OnLevelChanged", "OnVitaeChanged",
"OnTotalExperienceChanged", "OnAvailableLuminanceChanged",
};
private static readonly string[] TrainingNames = { "Unusable", "Untrained", "Trained", "Specialized" };
private static string TrainingName(int t) => t >= 0 && t < TrainingNames.Length ? TrainingNames[t] : "Unusable";
private static readonly Dictionary<int, string> SkillNameById = Reverse(LuaEnums.SkillId);
private static readonly Dictionary<int, string> AttributeNameById = Reverse(LuaEnums.AttributeId);
private static readonly Dictionary<int, string> VitalNameById = Reverse(LuaEnums.VitalId);
private static Dictionary<int, string> Reverse(Dictionary<string, int> map)
{
var r = new Dictionary<int, string>();
foreach (var kv in map) r[kv.Value] = kv.Key;
return r;
}
// ── Registration ────────────────────────────────────────────────────────
partial void RegisterCharacterApi(Script s, ScriptContext ctx, Table game)
{
var ch = new Table(s);
foreach (string e in CharacterEventNames)
ch[e] = ctx.Event("Character." + e).CreateTable(s);
// Vitals / Skills / Attributes: live objects, made once per script.
Table vitals = MakeVitals(s);
Table skills = MakeStatTable(s, "Skills", LuaEnums.SkillId, SkillNameById, MakeSkillMeta(s));
Table attributes = MakeStatTable(s, "Attributes", LuaEnums.AttributeId, AttributeNameById, MakeAttributeMeta(s));
ch["Vitals"] = DynValue.NewTable(vitals);
ch["Skills"] = DynValue.NewTable(skills);
ch["Attributes"] = DynValue.NewTable(attributes);
// The same objects on game.Character.Weenie (UB keeps the stats there).
s.Registry.Set("rynth.character.Vitals", DynValue.NewTable(vitals));
s.Registry.Set("rynth.character.Skills", DynValue.NewTable(skills));
s.Registry.Set("rynth.character.Attributes", DynValue.NewTable(attributes));
ch["Skill"] = DynValue.NewCallback((c, a) =>
{
int id = ResolveStat(LuaArgs.At(LuaArgs.Of(a, ch), 0), LuaEnums.SkillId, SkillNameById, "Skill", "\"WarMagic\" or SkillId.WarMagic");
return skills.Get(id);
});
ch["Attribute"] = DynValue.NewCallback((c, a) =>
{
int id = ResolveStat(LuaArgs.At(LuaArgs.Of(a, ch), 0), LuaEnums.AttributeId, AttributeNameById, "Attribute", "\"Strength\" or AttributeId.Strength");
return attributes.Get(id);
});
ch["Vital"] = DynValue.NewCallback((c, a) =>
{
int id = ResolveStat(LuaArgs.At(LuaArgs.Of(a, ch), 0), LuaEnums.VitalId, VitalNameById, "Vital", "\"Health\" or VitalId.Health");
return vitals.Get(VitalNameById[id]);
});
// Enchantments and the spellbook.
DynValue enchantments = DynValue.NewCallback((c, a) => ChEnchantmentList(s));
ch["Enchantments"] = enchantments;
// UB's names: every enchantment the client knows is active here (no layered/inactive split).
ch["ActiveEnchantments"] = enchantments;
ch["AllEnchantments"] = enchantments;
ch["HasEnchantment"] = DynValue.NewCallback((c, a) =>
DynValue.NewBoolean(ChHasEnchantment(LuaArgs.At(LuaArgs.Of(a, ch), 0))));
ch["KnowsSpell"] = DynValue.NewCallback((c, a) =>
DynValue.NewBoolean(ChKnowsSpell(ChSpellArg(LuaArgs.At(LuaArgs.Of(a, ch), 0), "KnowsSpell"))));
ch["IsBusy"] = DynValue.NewCallback((c, a) => DynValue.NewBoolean(ChBusy()));
ch["SpellBook"] = MakeSpellBook(s);
ch["Trade"] = CreateTradeTable(s, ctx);
var mt = new Table(s);
mt["__index"] = DynValue.NewCallback((c, a) =>
ChProperty(s, ctx, a.Count > 1 ? a[1].CastToString() ?? "" : ""));
mt["__tostring"] = DynValue.NewCallback((c, a) =>
{
uint pid = Host.GetPlayerId();
if (pid == 0) return DynValue.NewString("Character (not logged in)");
Host.TryGetObjectName(pid, out string name);
return DynValue.NewString($"Character {name} (0x{pid:X8})");
});
ch.MetaTable = mt;
// Inventory / Equipment / Containers (UB: list properties; still callable with a
// filter), GetInventory / GetFirstInventory / GetInventoryCount, InventoryCount: Lua
// glue over a few raw helpers, so filter functions run as plain Lua (they may even sleep).
InstallInventoryGlue(s, ctx, ch, game);
game["Character"] = DynValue.NewTable(ch);
}
/// <summary>game.Character.&lt;key&gt; for everything that isn't a raw field.</summary>
private DynValue ChProperty(Script s, ScriptContext ctx, string key)
{
uint pid = Host.GetPlayerId();
switch (key)
{
case "Id": return DynValue.NewNumber(pid);
case "Name": return DynValue.NewString(pid != 0 && Host.TryGetObjectName(pid, out string n) ? n : string.Empty);
case "Weenie": return WrapObject(s, ctx, pid);
case "Level": return DynValue.NewNumber(ChInt(ChIntLevel));
case "CombatMode": return DynValue.NewNumber(Host.GetCurrentCombatMode());
case "CombatModeName": return DynValue.NewString(LuaEnums.CombatModeName(Host.GetCurrentCombatMode()));
case "InPortalSpace": return DynValue.NewBoolean(Host.HasIsPortaling && Host.IsPortaling());
case "Vitae": return DynValue.NewNumber(pid != 0 && Host.HasGetVitae ? Host.GetVitae(pid) : 1.0);
case "Busy": return DynValue.NewBoolean(ChBusy());
case "Health": return DynValue.NewNumber(ChVitalCurrent(1));
case "Stamina": return DynValue.NewNumber(ChVitalCurrent(3));
case "Mana": return DynValue.NewNumber(ChVitalCurrent(5));
case "MaxHealth": return DynValue.NewNumber(ChVitalMax(1));
case "MaxStamina": return DynValue.NewNumber(ChVitalMax(3));
case "MaxMana": return DynValue.NewNumber(ChVitalMax(5));
case "BurdenUnits": return DynValue.NewNumber(ChInt(ChIntEncumbrance));
case "MaxBurdenUnits": return DynValue.NewNumber(ChBurdenCapacity());
case "Burden":
{
long cap = ChBurdenCapacity();
return DynValue.NewNumber(cap > 0 ? ChInt(ChIntEncumbrance) * 100.0 / cap : 0);
}
case "TotalExperience": return DynValue.NewNumber(ChInt64(ChInt64TotalXp));
case "UnassignedExperience": return DynValue.NewNumber(ChInt64(ChInt64UnassignedXp));
case "AvailableLuminance": return DynValue.NewNumber(ChInt64(ChInt64AvailableLum));
case "MaximumLuminance": return DynValue.NewNumber(ChInt64(ChInt64MaxLum));
default: return DynValue.Nil;
}
}
// ── SDK reads ───────────────────────────────────────────────────────────
private int ChInt(uint stype)
{
uint pid = Host.GetPlayerId();
return pid != 0 && Host.HasGetObjectIntProperty && Host.TryGetObjectIntProperty(pid, stype, out int v) ? v : 0;
}
private long ChInt64(uint stype)
{
uint pid = Host.GetPlayerId();
return pid != 0 && Host.HasGetObjectQuadProperty && Host.TryGetObjectQuadProperty(pid, stype, out long v) ? v : 0;
}
private bool ChBusy() => Host.GetBusyState() != 0 || Host.GetCastBusyState() != 0;
/// <summary>AC's carrying capacity: 150 per point of Strength, +30 per point per capacity augmentation.</summary>
private long ChBurdenCapacity()
{
uint str = ChAttribute(1, raw: false);
if (str == 0) return 0;
int augs = Math.Max(0, ChInt(ChIntAugCarrying));
return str * (150L + 30L * augs);
}
private bool ChReadVitals(out uint hp, out uint maxHp, out uint st, out uint maxSt, out uint mana, out uint maxMana)
{
hp = maxHp = st = maxSt = mana = maxMana = 0;
return Host.HasGetPlayerVitals && Host.TryGetPlayerVitals(out hp, out maxHp, out st, out maxSt, out mana, out maxMana);
}
private uint ChVitalCurrent(int vital)
{
if (!ChReadVitals(out uint hp, out _, out uint st, out _, out uint mana, out _)) return 0;
return vital switch { 1 => hp, 3 => st, _ => mana };
}
/// <summary>Buffed maximum (InqAttribute2nd, live), else the vitals snapshot's max.</summary>
private uint ChVitalMax(int vital)
{
uint pid = Host.GetPlayerId();
uint stype2nd = vital switch { 1 => 1u, 3 => 3u, _ => 5u }; // VitalId is AC's max-vital id
if (pid != 0 && Host.HasGetObjectAttribute2ndBaseLevel && Host.TryGetObjectAttribute2ndBaseLevel(pid, stype2nd, out uint max) && max > 0)
return max;
if (!ChReadVitals(out _, out uint maxHp, out _, out uint maxSt, out _, out uint maxMana)) return 0;
return vital switch { 1 => maxHp, 3 => maxSt, _ => maxMana };
}
/// <summary>Unbuffed maximum (from attributes and raised points, no enchantments).</summary>
private uint ChVitalBase(int vital)
{
if (!Host.HasGetPlayerBaseVitals || !Host.TryGetPlayerBaseVitals(out uint hp, out uint st, out uint mana)) return 0;
return vital switch { 1 => hp, 3 => st, _ => mana };
}
private int ChSkillCurrent(int skill)
{
uint pid = Host.GetPlayerId();
if (pid == 0) return 0;
if (Host.HasGetObjectSkillBuffed && Host.TryGetObjectSkillLevel(pid, (uint)skill, 0, out int level)) return level;
return Host.HasGetObjectSkill && Host.TryGetObjectSkill(pid, (uint)skill, out int buffed, out _) ? buffed : 0;
}
private int ChSkillBase(int skill)
{
uint pid = Host.GetPlayerId();
return pid != 0 && Host.HasGetObjectSkillBuffed && Host.TryGetObjectSkillLevel(pid, (uint)skill, 1, out int level) ? level : 0;
}
private int ChSkillTraining(int skill)
{
uint pid = Host.GetPlayerId();
return pid != 0 && Host.HasGetObjectSkill && Host.TryGetObjectSkill(pid, (uint)skill, out _, out int training) ? training : 0;
}
private uint ChAttribute(int attribute, bool raw)
{
uint pid = Host.GetPlayerId();
return pid != 0 && Host.HasGetObjectAttribute && Host.TryGetObjectAttribute(pid, (uint)attribute, raw ? 1 : 0, out uint v) ? v : 0;
}
// ── Vitals / Skills / Attributes objects ────────────────────────────────
/// <summary>A number (LuaEnums id) or a name ("WarMagic", "war magic") → id; anything else is an error.</summary>
private static int ResolveStat(DynValue v, Dictionary<string, int> byName, Dictionary<int, string> byId, string what, string example)
{
if (v.Type == DataType.Number && byId.ContainsKey((int)v.Number)) return (int)v.Number;
if (v.Type == DataType.String && byName.TryGetValue(v.String.Replace(" ", ""), out int id)) return id;
throw new ScriptRuntimeException($"{what}({(v.IsNil() ? "" : v.ToPrintString())}): unknown {what.ToLowerInvariant()}; use a name or number, e.g. {example}");
}
private static int StatId(CallbackArguments a) =>
a.Count > 0 && a[0].Type == DataType.Table && a[0].Table.Get("Id").Type == DataType.Number ? (int)a[0].Table.Get("Id").Number : 0;
private static string KeyOf(CallbackArguments a) => a.Count > 1 ? a[1].CastToString() ?? "" : "";
/// <summary>A table holding one live object per id (numeric keys, so pairs() lists them); names resolve through __index.</summary>
private static Table MakeStatTable(Script s, string label, Dictionary<string, int> byName, Dictionary<int, string> byId, Table objMeta)
{
var t = new Table(s);
foreach (var kv in byId)
{
var o = new Table(s);
o["Id"] = (double)kv.Key;
o["Type"] = (double)kv.Key; // UB's name for the id
o["Name"] = kv.Value;
o.MetaTable = objMeta;
t.Set(kv.Key, DynValue.NewTable(o));
}
var mt = new Table(s);
mt["__index"] = DynValue.NewCallback((c, a) =>
{
DynValue k = a.Count > 1 ? a[1] : DynValue.Nil;
if (k.Type == DataType.String && byName.TryGetValue(k.String.Replace(" ", ""), out int id)) return t.Get(id);
return DynValue.Nil;
});
mt["__tostring"] = DynValue.NewCallback((c, a) => DynValue.NewString(label));
t.MetaTable = mt;
return t;
}
private Table MakeSkillMeta(Script s)
{
var mt = new Table(s);
mt["__index"] = DynValue.NewCallback((c, a) =>
{
int id = StatId(a);
return KeyOf(a) switch
{
"Current" => DynValue.NewNumber(ChSkillCurrent(id)),
"Base" => DynValue.NewNumber(ChSkillBase(id)),
"Training" => DynValue.NewNumber(ChSkillTraining(id)),
"TrainingName" => DynValue.NewString(TrainingName(ChSkillTraining(id))),
"IsTrained" => DynValue.NewBoolean(ChSkillTraining(id) >= 2),
_ => DynValue.Nil,
};
});
mt["__tostring"] = DynValue.NewCallback((c, a) =>
{
int id = StatId(a);
string name = SkillNameById.TryGetValue(id, out string? n) ? n : id.ToString();
return DynValue.NewString($"Skill {name}: {ChSkillCurrent(id)} (base {ChSkillBase(id)}, {TrainingName(ChSkillTraining(id))})");
});
return mt;
}
private Table MakeAttributeMeta(Script s)
{
var mt = new Table(s);
mt["__index"] = DynValue.NewCallback((c, a) =>
{
int id = StatId(a);
return KeyOf(a) switch
{
"Current" => DynValue.NewNumber(ChAttribute(id, raw: false)),
"Base" => DynValue.NewNumber(ChAttribute(id, raw: true)),
_ => DynValue.Nil,
};
});
mt["__tostring"] = DynValue.NewCallback((c, a) =>
{
int id = StatId(a);
string name = AttributeNameById.TryGetValue(id, out string? n) ? n : id.ToString();
return DynValue.NewString($"Attribute {name}: {ChAttribute(id, false)} (base {ChAttribute(id, true)})");
});
return mt;
}
/// <summary>Vitals.Health / .Stamina / .Mana (raw fields), Vitals[VitalId] through __index.</summary>
private Table MakeVitals(Script s)
{
var objMeta = new Table(s);
objMeta["__index"] = DynValue.NewCallback((c, a) =>
{
int id = StatId(a);
return KeyOf(a) switch
{
"Current" => DynValue.NewNumber(ChVitalCurrent(id)),
"Max" => DynValue.NewNumber(ChVitalMax(id)),
"Base" => DynValue.NewNumber(ChVitalBase(id)),
_ => DynValue.Nil,
};
});
objMeta["__tostring"] = DynValue.NewCallback((c, a) =>
{
int id = StatId(a);
return DynValue.NewString($"{VitalNameById[id]} {ChVitalCurrent(id)}/{ChVitalMax(id)}");
});
var t = new Table(s);
foreach (var kv in VitalNameById)
{
var o = new Table(s);
o["Id"] = (double)kv.Key;
o["Type"] = (double)kv.Key; // UB's name for the id
o["Name"] = kv.Value;
o.MetaTable = objMeta;
t[kv.Value] = DynValue.NewTable(o);
}
var mt = new Table(s);
mt["__index"] = DynValue.NewCallback((c, a) =>
{
DynValue k = a.Count > 1 ? a[1] : DynValue.Nil;
if (k.Type == DataType.Number && VitalNameById.TryGetValue((int)k.Number, out string? name)) return t.Get(name);
if (k.Type == DataType.String && LuaEnums.VitalId.TryGetValue(k.String, out int id)) return t.Get(VitalNameById[id]);
return DynValue.Nil;
});
mt["__tostring"] = DynValue.NewCallback((c, a) => DynValue.NewString(
$"Vitals: Health {ChVitalCurrent(1)}/{ChVitalMax(1)}, Stamina {ChVitalCurrent(3)}/{ChVitalMax(3)}, Mana {ChVitalCurrent(5)}/{ChVitalMax(5)}"));
t.MetaTable = mt;
return t;
}
// ── Spellbook ───────────────────────────────────────────────────────────
private readonly HashSet<uint> _chKnownSpells = new();
private long _chKnownSpellsAt;
private readonly Dictionary<uint, string?> _chSpellNames = new();
private static uint ChSpellArg(DynValue v, string what)
{
if (v.Type == DataType.Number && v.Number > 0) return (uint)v.Number & 0xFFFF;
throw new ScriptRuntimeException($"{what}(spellId) needs a spell id (a number)");
}
/// <summary>
/// The spellbook snapshot the engine reads on AC's main thread (ReadKnownSpells), refreshed
/// at most every 3 s (1 s while it is still empty). The per-spell IsSpellKnown call is not
/// used: it answers "known" for spells the character doesn't have.
/// </summary>
private void ChRefreshKnownSpells()
{
long now = Environment.TickCount64;
if (now - _chKnownSpellsAt < (_chKnownSpells.Count > 0 ? 3000 : 1000)) return;
_chKnownSpellsAt = now;
if (!Host.HasReadKnownSpells || Host.GetPlayerId() == 0) return;
int cap = 4096, n;
uint[] buf;
while (true)
{
buf = new uint[cap];
n = Host.ReadKnownSpells(buf, cap);
if (n < cap || cap >= 65536) break; // a full buffer means the list was cut short
cap *= 2;
}
if (n <= 0) return; // cold or unavailable: keep what we had
_chKnownSpells.Clear();
for (int i = 0; i < Math.Min(n, buf.Length); i++)
if (buf[i] != 0) _chKnownSpells.Add(buf[i]);
}
/// <summary>For game.Actions' CastSpell check: null while the spellbook snapshot is still empty.</summary>
internal bool? KnowsSpellIfLoaded(uint spellId)
{
ChRefreshKnownSpells();
return _chKnownSpells.Count == 0 ? null : _chKnownSpells.Contains(spellId);
}
private bool ChKnowsSpell(uint spellId)
{
ChRefreshKnownSpells();
return _chKnownSpells.Contains(spellId);
}
/// <summary>Spell name from RynthAi's spell table (null without RynthAi or for unknown ids).</summary>
private string? ChSpellName(uint spellId)
{
if (_chSpellNames.TryGetValue(spellId, out string? cached)) return cached;
if (!_ai.Available) return null; // not cached: RynthAi may load later
string? name = null;
if (_ai.Evaluate($"spellname[{spellId}]", out string r) && r.Length > 0
&& !r.StartsWith("Unknown Spell", StringComparison.OrdinalIgnoreCase))
name = r;
_chSpellNames[spellId] = name;
return name;
}
private DynValue MakeSpellBook(Script s)
{
var sb = new Table(s);
sb["IsKnown"] = DynValue.NewCallback((c, a) =>
DynValue.NewBoolean(ChKnowsSpell(ChSpellArg(LuaArgs.At(LuaArgs.Of(a, sb), 0), "SpellBook.IsKnown"))));
sb["KnownSpellIds"] = DynValue.NewCallback((c, a) =>
{
ChRefreshKnownSpells();
var ids = new List<uint>(_chKnownSpells);
ids.Sort();
var t = new Table(s);
for (int i = 0; i < ids.Count; i++) t.Set(i + 1, DynValue.NewNumber(ids[i]));
return DynValue.NewTable(t);
});
sb["Name"] = DynValue.NewCallback((c, a) =>
{
string? name = ChSpellName(ChSpellArg(LuaArgs.At(LuaArgs.Of(a, sb), 0), "SpellBook.Name"));
return name == null ? DynValue.Nil : DynValue.NewString(name);
});
var mt = new Table(s);
mt["__index"] = DynValue.NewCallback((c, a) =>
{
switch (KeyOf(a))
{
case "Count":
ChRefreshKnownSpells();
return DynValue.NewNumber(_chKnownSpells.Count);
case "KnownSpellsIds": // UB's property (sorted list)
{
ChRefreshKnownSpells();
var ids = new List<uint>(_chKnownSpells);
ids.Sort();
return IdList(s, ids);
}
default:
return DynValue.Nil;
}
});
mt["__tostring"] = DynValue.NewCallback((c, a) => DynValue.NewString($"SpellBook ({_chKnownSpells.Count} spells)"));
sb.MetaTable = mt;
return DynValue.NewTable(sb);
}
// ── Enchantments ────────────────────────────────────────────────────────
private const int ChMaxEnchantments = 512;
private readonly uint[] _chEnchIds = new uint[ChMaxEnchantments];
private readonly double[] _chEnchExp = new double[ChMaxEnchantments];
private readonly List<(uint SpellId, double Expiry)> _chEnchLastGood = new();
/// <summary>Durations seen in OnEnchantmentAdded (the registry read only has expiry times).</summary>
private readonly Dictionary<uint, double> _chEnchDuration = new();
/// <summary>
/// The player's enchantments (spell id, expiry in server seconds; double.MaxValue for
/// permanent ones). The engine refuses a read that races AC's own update (-1); then the
/// last good read is used.
/// </summary>
private List<(uint SpellId, double Expiry)> ChReadEnchantments(out bool fresh)
{
fresh = false;
if (!Host.HasReadPlayerEnchantments || Host.GetPlayerId() == 0) return _chEnchLastGood;
for (int attempt = 0; attempt < 2; attempt++)
{
int n = Host.ReadPlayerEnchantments(_chEnchIds, _chEnchExp, ChMaxEnchantments);
if (n < 0) continue;
_chEnchLastGood.Clear();
for (int i = 0; i < Math.Min(n, ChMaxEnchantments); i++)
_chEnchLastGood.Add((_chEnchIds[i], _chEnchExp[i]));
fresh = true;
break;
}
return _chEnchLastGood;
}
private static bool ChPermanent(double expiry) => expiry >= double.MaxValue / 2;
/// <summary>{SpellId, Name, Remaining, ExpiresAt, Duration, Permanent} for one enchantment.</summary>
private DynValue ChEnchantmentTable(Script s, uint spellId, double expiry, double serverNow, double unixNow)
{
var t = new Table(s);
t["SpellId"] = (double)spellId;
string? name = ChSpellName(spellId);
if (name != null) t["Name"] = name;
bool permanent = ChPermanent(expiry);
t["Permanent"] = permanent;
if (permanent)
{
t["Remaining"] = double.PositiveInfinity;
t["ExpiresAt"] = double.PositiveInfinity;
t["Duration"] = -1.0;
}
else
{
if (serverNow > 0)
{
double remaining = Math.Max(0, expiry - serverNow);
t["Remaining"] = remaining;
t["ExpiresAt"] = unixNow + remaining;
}
if (_chEnchDuration.TryGetValue(spellId, out double d) && d > 0) t["Duration"] = d;
}
return DynValue.NewTable(t);
}
private static double UnixNow() => DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() / 1000.0;
private DynValue ChEnchantmentList(Script s)
{
var list = ChReadEnchantments(out _);
double serverNow = Host.HasGetServerTime ? Host.GetServerTime() : 0;
double unixNow = UnixNow();
var t = new Table(s);
int i = 1;
foreach (var (id, exp) in list)
t.Set(i++, ChEnchantmentTable(s, id, exp, serverNow, unixNow));
return LuaLists.Wrap(s, t);
}
/// <summary>HasEnchantment(spellId) or HasEnchantment("Spell Name") (names need RynthAi).</summary>
private bool ChHasEnchantment(DynValue v)
{
if (v.Type == DataType.Number)
{
uint id = (uint)v.Number & 0xFFFF;
foreach (var e in ChReadEnchantments(out _)) if (e.SpellId == id) return true;
return false;
}
if (v.Type == DataType.String)
{
foreach (var e in ChReadEnchantments(out _))
if (string.Equals(ChSpellName(e.SpellId), v.String, StringComparison.OrdinalIgnoreCase)) return true;
return false;
}
throw new ScriptRuntimeException("HasEnchantment(spellId) needs a spell id (or a spell name)");
}
// ── Inventory / Equipment ───────────────────────────────────────────────
private readonly uint[] _chIdBuf = new uint[512];
/// <summary>What the character carries in packs: main-pack items, side packs, and the side packs' contents.</summary>
private List<uint> ChPackIds(bool containersOnly)
{
var result = new List<uint>();
uint pid = Host.GetPlayerId();
if (pid == 0 || !Host.HasGetContainerContents) return result;
// Warms the engine's physics-object offset probe that container reads rely on (as RynthAi does).
Host.TryGetObjectPosition(pid, out _, out _, out _, out _);
int n = Host.GetContainerContents(pid, _chIdBuf);
var packs = new List<uint>();
for (int i = 0; i < n; i++)
{
uint id = _chIdBuf[i];
bool isPack = Host.TryGetItemType(id, out uint flags) && (flags & ChItemTypeContainer) != 0;
if (isPack) packs.Add(id);
if (!containersOnly || isPack) result.Add(id);
}
if (containersOnly) return result;
foreach (uint pack in packs)
{
int m = Host.GetContainerContents(pack, _chIdBuf);
for (int i = 0; i < m; i++) result.Add(_chIdBuf[i]);
}
return result;
}
private uint ChWielderOf(uint id)
{
if (Host.HasGetObjectWielderInfo && Host.TryGetObjectWielderInfo(id, out uint w, out _) && w != 0) return w;
if (Host.HasGetObjectOwnershipInfo && Host.TryGetObjectOwnershipInfo(id, out _, out uint w2, out _)) return w2;
return 0;
}
private static DynValue IdArray(Script s, List<uint> ids)
{
var t = new Table(s);
for (int i = 0; i < ids.Count; i++) t.Set(i + 1, DynValue.NewNumber(ids[i]));
return DynValue.NewTable(t);
}
/// <summary>
/// Inventory([filter]), Equipment([filter]), Containers([filter]), InventoryCount(nameOrFilter).
/// Packs come from the engine's container lists; worn/wielded items aren't in those, so
/// they come from game.World's object list (every object whose wielder is you).
/// </summary>
private void InstallInventoryGlue(Script s, ScriptContext ctx, Table ch, Table game)
{
DynValue packIds = DynValue.NewCallback((c, a) => IdArray(s, ChPackIds(containersOnly: false)));
DynValue containerIds = DynValue.NewCallback((c, a) => IdArray(s, ChPackIds(containersOnly: true)));
DynValue wielderOf = DynValue.NewCallback((c, a) =>
DynValue.NewNumber(ChWielderOf(LuaArgs.Id(a.Count > 0 ? a[0] : DynValue.Nil))));
DynValue nameOf = DynValue.NewCallback((c, a) =>
{
uint id = LuaArgs.Id(a.Count > 0 ? a[0] : DynValue.Nil);
return id != 0 && Host.TryGetObjectName(id, out string n) ? DynValue.NewString(n) : DynValue.Nil;
});
DynValue stackOf = DynValue.NewCallback((c, a) =>
{
uint id = LuaArgs.Id(a.Count > 0 ? a[0] : DynValue.Nil);
int n = id != 0 && Host.HasGetObjectIntProperty && Host.TryGetObjectIntProperty(id, ChIntStackSize, out int v) ? v : 0;
return DynValue.NewNumber(n > 0 ? n : 1);
});
DynValue wrap = DynValue.NewCallback((c, a) => WrapObject(s, ctx, LuaArgs.Id(a.Count > 0 ? a[0] : DynValue.Nil)));
DynValue wieldedIds = DynValue.NewCallback((c, a) => IdArray(s, WorldWieldedIds(Host.GetPlayerId())));
var classNames = new Table(s);
for (int i = 0; i < LuaEnums.ObjectClass.Length; i++) classNames.Set(DynValue.NewNumber(i), DynValue.NewString(LuaEnums.ObjectClass[i]));
DynValue install = s.LoadString(InventoryGlue, null, "game.Character");
s.Call(install, DynValue.NewTable(ch), DynValue.NewTable(game), packIds, containerIds, wielderOf,
nameOf, stackOf, wrap, DynValue.NewTable(classNames), wieldedIds, LuaLists.MakeFunction(s));
}
private const string InventoryGlue = """
local C, G, packIds, containerIds, wielderOf, nameOf, stackOf, wrap, classNames, wieldedIds, makeList = ...
-- Exact ObjectClass names ("Portal", "Monster") filter by class, as game.World does.
local classByName = {}
for i, n in pairs(classNames) do classByName[n] = i end
-- A filter is a name substring, an ObjectClass value or function(wo) -> bool.
-- Returns how to test ('id': by object id, cheap; 'wo': on the object) and the test.
local function filterOf(f, what)
if f == nil then return nil, nil end
local t = type(f)
if t == 'string' and classByName[f] ~= nil then
f, t = classByName[f], 'number'
end
if t == 'string' then
local needle = string.lower(f)
return 'id', function(id)
local n = nameOf(id)
return n ~= nil and string.find(string.lower(n), needle, 1, true) ~= nil
end
elseif t == 'number' then
return 'wo', function(wo)
local oc = wo.ObjectClass
if type(oc) == 'string' then return oc == classNames[f] end
return oc == f
end
elseif t == 'function' then
return 'wo', function(wo) return f(wo) and true or false end
end
error(what .. '(filter): a filter is a name, an ObjectClass value or a function(wo) that returns true', 0)
end
local function add(out, seen, id, kind, test, wo)
if seen[id] then return end
if kind == 'id' and not test(id) then return end
wo = wo or wrap(id)
if wo == nil then return end
if kind == 'wo' and not test(wo) then return end
seen[id] = true
out[#out + 1] = wo
end
local function fromPacks(ids, kind, test, out, seen)
for i = 1, #ids do add(out, seen, ids[i], kind, test) end
end
-- Worn and wielded items aren't in any container list: game.World's known objects
-- whose wielder is you.
local function fromEquipment(kind, test, out, seen)
local ids = wieldedIds()
for i = 1, #ids do add(out, seen, ids[i], kind, test) end
end
local function inventory(a, what)
local kind, test = filterOf(a, what)
local out, seen = {}, {}
fromPacks(packIds(), kind, test, out, seen)
fromEquipment(kind, test, out, seen)
return out
end
local function equipment(a)
local kind, test = filterOf(a, 'Equipment')
local out = {}
fromEquipment(kind, test, out, {})
return out
end
local function containers(a)
local kind, test = filterOf(a, 'Containers')
local out = {}
fromPacks(containerIds(), kind, test, out, {})
return out
end
local function count(a, what)
if a == nil then error(what .. '(nameOrFilter) needs a name, an ObjectClass value or a function(wo)', 0) end
local items = inventory(a, what)
local n = 0
for i = 1, #items do n = n + stackOf(items[i].Id) end
return n
end
-- Inventory / Equipment / Containers: UB's list properties. The list can still be called
-- with a filter, RynthLua's older form: game.Character.Inventory("Potion").
local function callable(build)
return function(a, b)
if rawequal(a, C) then a = b end
return makeList(build(a))
end
end
local lists = {
Inventory = function(a) return inventory(a, 'Inventory') end,
Equipment = equipment,
Containers = containers,
}
local mt = getmetatable(C)
local clrIndex = mt.__index
mt.__index = function(t, k)
local build = lists[k]
if build ~= nil then return makeList(build(nil), callable(build)) end
return clrIndex(t, k)
end
-- UB's searches: GetInventory(filter) (a list), GetFirstInventory(filter) (the first match or
-- nil), GetInventoryCount(filter) (stack sizes added up). A filter is a name, an ObjectClass
-- or a function(wo).
function C.GetInventory(a, b)
if rawequal(a, C) then a = b end
if a == nil then error('GetInventory(filter) needs a name, an ObjectClass value or a function(wo)', 0) end
return makeList(inventory(a, 'GetInventory'))
end
function C.GetFirstInventory(a, b)
if rawequal(a, C) then a = b end
if a == nil then error('GetFirstInventory(filter) needs a name, an ObjectClass value or a function(wo)', 0) end
return inventory(a, 'GetFirstInventory')[1]
end
function C.GetInventoryCount(a, b)
if rawequal(a, C) then a = b end
return count(a, 'GetInventoryCount')
end
function C.InventoryCount(a, b)
if rawequal(a, C) then a = b end
return count(a, 'InventoryCount')
end
""";
}

View file

@ -0,0 +1,395 @@
using System;
using System.Collections.Generic;
using MoonSharp.Interpreter;
namespace RynthCore.Plugin.RynthLua;
/// <summary>
/// game.Character events. The engine raises combat mode changes, and enchantment changes on
/// API v70+ (older engines never call OnEnchantmentAdded/Removed); the rest is found by
/// polling in <see cref="CharacterTick"/>: vitals and portal space every tick (one cheap SDK
/// call each), level, experience and vitae every 500 ms, enchantments every 500 ms on older
/// engines. Level, experience and enchantments only while some script listens (a poll that
/// nobody listens to forgets its baseline, so a script that starts listening later doesn't
/// get a burst of stale changes).
///
/// Death has no engine event: health reaching 0, vitae dropping, or a death line in chat,
/// whichever comes first; OnDeath fires once per death (30 s window), with the chat line as
/// Text when one came.
/// </summary>
public sealed partial class RynthLuaPlugin
{
private uint _chPlayer;
private long _chBaselineAt;
private bool _chVitalsKnown;
private uint _chHp, _chStam, _chMana;
private bool _chPortalKnown, _chPortal;
private long _chNextSlow;
private bool _chEnchKnown, _chEnchDirty;
private long _chEnchNextCheck;
private Dictionary<uint, double> _chEnch = new();
private Dictionary<uint, double> _chEnchScratch = new();
/// <summary>Spell ids the engine reported as added since the last diff (API v70+).</summary>
private readonly HashSet<uint> _chEnchEventAdds = new();
private bool _chLevelKnown; private int _chLevel;
private bool _chXpKnown; private long _chXp;
private bool _chLumKnown; private long _chLum;
private bool _chVitaeKnown; private float _chVitae;
private long _chDeathPendingAt, _chLastDeathAt = long.MinValue / 2, _chDeathTextAt = long.MinValue / 2;
private string _chDeathText = string.Empty;
private const long ChSlowPollMs = 500;
/// <summary>With engine enchantment events: a safety re-read this often (events do the rest).</summary>
private const long ChEnchReconcileMs = 10000;
private const long ChDeathWindowMs = 30000;
private const long ChLoginSettleMs = 10000;
private void ChReset(uint playerId)
{
_chPlayer = playerId;
_chBaselineAt = Environment.TickCount64;
_chVitalsKnown = _chPortalKnown = _chEnchKnown = _chLevelKnown = _chXpKnown = _chVitaeKnown = _chLumKnown = false;
_chEnchDirty = false;
_chEnchNextCheck = 0;
_chEnchEventAdds.Clear();
_chEnch.Clear();
_chEnchDuration.Clear();
_chEnchLastGood.Clear();
_chKnownSpells.Clear();
_chKnownSpellsAt = 0;
_chDeathPendingAt = 0;
_chNextSlow = 0;
}
private bool ChListens(string key)
{
foreach (var c in _scripts.Values)
if (c.Host.Loaded && c.HasHandlers(key)) return true;
return false;
}
partial void CharacterOnLogin() { _chCombatMode = -1; ChReset(Host.GetPlayerId()); }
partial void CharacterOnLogout() { _chCombatMode = -1; ChReset(0); }
partial void CharacterTick()
{
if (GameState != "InGame") return;
uint pid = Host.GetPlayerId();
if (pid == 0) return;
if (pid != _chPlayer) ChReset(pid);
long now = Environment.TickCount64;
bool settled = now - _chBaselineAt >= ChLoginSettleMs;
// Combat mode (every tick): the engine's change event can miss a change, so the
// client's current mode is watched too; ChCombatModeChanged drops duplicates.
if (Host.HasGetCurrentCombatMode)
{
int mode = Host.GetCurrentCombatMode();
if (_chCombatMode <= 0) _chCombatMode = mode;
else if (mode > 0 && mode != _chCombatMode) ChCombatModeChanged(mode, _chCombatMode);
}
// Portal space (every tick).
bool portaling = Host.HasIsPortaling && Host.IsPortaling();
if (Host.HasIsPortaling)
{
if (_chPortalKnown && portaling != _chPortal)
FireAll(portaling ? "Character.OnPortalSpaceEntered" : "Character.OnPortalSpaceExited",
s => DynValue.NewTable(new Table(s)));
_chPortal = portaling;
_chPortalKnown = true;
}
// Vitals (every tick). A read with every max at 0 is "not loaded yet", not a change.
if (ChReadVitals(out uint hp, out uint maxHp, out uint st, out uint maxSt, out uint mana, out uint maxMana)
&& (maxHp | maxSt | maxMana) != 0)
{
if (_chVitalsKnown)
{
if (hp != _chHp) ChFireVital(1, hp, _chHp);
if (st != _chStam) ChFireVital(3, st, _chStam); // VitalId numbering (1, 3, 5)
if (mana != _chMana) ChFireVital(5, mana, _chMana);
if (_chHp > 0 && hp == 0 && maxHp > 0 && !portaling && settled) ChDeathSignal(now);
}
_chHp = hp; _chStam = st; _chMana = mana;
_chVitalsKnown = true;
}
if (_chDeathPendingAt != 0 && now >= _chDeathPendingAt)
ChFireDeath(now, now - _chDeathTextAt < 5000 ? _chDeathText : string.Empty);
// Enchantments. On API v70+ the engine's events mark them dirty and the diff runs on
// the next tick; a slow re-read catches anything an event could miss. Older engines
// poll every 500 ms. Either way one diff against the last read decides what fired,
// so an event and a poll can never report the same change twice.
if (_chEnchDirty || now >= _chEnchNextCheck)
{
if (ChListens("Character.OnEnchantmentsChanged"))
{
if (ChPollEnchantments())
{
_chEnchDirty = false;
_chEnchNextCheck = now + (Host.HasEnchantmentEvents ? ChEnchReconcileMs : ChSlowPollMs);
}
// The read raced AC's own update: an event waiting keeps it dirty for the next tick.
else if (!_chEnchDirty) _chEnchNextCheck = now + ChSlowPollMs;
}
else
{
_chEnchKnown = false;
_chEnchDirty = false;
_chEnchEventAdds.Clear();
_chEnchNextCheck = now + ChSlowPollMs;
}
}
if (now < _chNextSlow) return;
_chNextSlow = now + ChSlowPollMs;
// Vitae: always (a drop is a death signal); OnVitaeChanged when listened to.
if (Host.HasGetVitae)
{
float vitae = Host.GetVitae(pid);
if (_chVitaeKnown && Math.Abs(vitae - _chVitae) > 0.0001f)
{
if (vitae < _chVitae && settled) ChDeathSignal(now);
float old = _chVitae;
FireAll("Character.OnVitaeChanged", s =>
{
var t = new Table(s);
t["Vitae"] = (double)vitae;
t["OldVitae"] = (double)old;
return DynValue.NewTable(t);
});
}
_chVitae = vitae;
_chVitaeKnown = true;
}
if (ChListens("Character.OnLevelChanged"))
{
int level = ChInt(ChIntLevel);
if (level > 0)
{
if (_chLevelKnown && level != _chLevel)
{
int old = _chLevel;
FireAll("Character.OnLevelChanged", s =>
{
var t = new Table(s);
t["Level"] = (double)level;
t["OldLevel"] = (double)old;
return DynValue.NewTable(t);
});
}
_chLevel = level;
_chLevelKnown = true;
}
}
else _chLevelKnown = false;
if (ChListens("Character.OnTotalExperienceChanged"))
{
long xp = ChInt64(ChInt64TotalXp);
if (xp > 0)
{
if (_chXpKnown && xp != _chXp)
{
long old = _chXp;
FireAll("Character.OnTotalExperienceChanged", s =>
{
var t = new Table(s);
t["TotalExperience"] = (double)xp;
t["OldTotalExperience"] = (double)old;
return DynValue.NewTable(t);
});
}
_chXp = xp;
_chXpKnown = true;
}
}
else _chXpKnown = false;
if (ChListens("Character.OnAvailableLuminanceChanged"))
{
long lum = ChInt64(ChInt64AvailableLum);
if (_chLumKnown && lum != _chLum)
{
long old = _chLum;
FireAll("Character.OnAvailableLuminanceChanged", s =>
{
var t = new Table(s);
t["AvailableLuminance"] = (double)lum;
t["OldAvailableLuminance"] = (double)old;
return DynValue.NewTable(t);
});
}
_chLum = lum;
_chLumKnown = true;
}
else _chLumKnown = false;
}
private void ChFireVital(int vital, uint value, uint oldValue)
{
FireAll("Character.OnVitalChanged", s =>
{
var t = new Table(s);
t["Type"] = (double)vital;
t["TypeName"] = VitalNameById[vital];
t["Value"] = (double)value;
t["OldValue"] = (double)oldValue;
return DynValue.NewTable(t);
});
}
// ── Enchantments ────────────────────────────────────────────────────────
/// <summary>
/// Diffs the enchantment registry against the last read: a new spell id is "Added", a
/// spell whose expiry moved later (recast) is "Added" with Refreshed = true, a spell that
/// is gone is "Removed". One event per enchantment, like UtilityBelt. On API v70+ it runs
/// when the engine reports a change, and a spell the engine reported as added that was
/// already there is "Added" with Refreshed = true even when its expiry didn't move (a
/// recast inside the same second). False when the registry couldn't be read this time.
/// </summary>
private bool ChPollEnchantments()
{
var list = ChReadEnchantments(out bool fresh);
if (!fresh) return false;
var cur = _chEnchScratch;
cur.Clear();
foreach (var (id, exp) in list)
if (!cur.TryGetValue(id, out double old) || exp > old) cur[id] = exp;
if (_chEnchKnown)
{
double serverNow = Host.HasGetServerTime ? Host.GetServerTime() : 0;
double unixNow = UnixNow();
foreach (var kv in cur)
{
if (!_chEnch.TryGetValue(kv.Key, out double oldExp))
ChFireEnchantment("Added", kv.Key, kv.Value, refreshed: false, serverNow, unixNow);
else if ((kv.Value > oldExp + 1.0 && !ChPermanent(oldExp)) || _chEnchEventAdds.Contains(kv.Key))
ChFireEnchantment("Added", kv.Key, kv.Value, refreshed: true, serverNow, unixNow);
}
foreach (var kv in _chEnch)
if (!cur.ContainsKey(kv.Key))
ChFireEnchantment("Removed", kv.Key, kv.Value, refreshed: false, serverNow, unixNow);
}
_chEnchEventAdds.Clear();
_chEnchScratch = _chEnch;
_chEnch = cur;
_chEnchKnown = true;
return true;
}
private void ChFireEnchantment(string type, uint spellId, double expiry, bool refreshed, double serverNow, double unixNow)
{
FireAll("Character.OnEnchantmentsChanged", s =>
{
var t = new Table(s);
t["Type"] = type == "Added" ? 0.0 : 1.0; // UB's AddRemoveEventType
t["TypeName"] = type;
t["SpellId"] = (double)spellId;
string? name = ChSpellName(spellId);
if (name != null) t["Name"] = name;
t["Refreshed"] = refreshed;
var layered = new Table(s);
layered["Id"] = (double)spellId; // UB's LayeredSpellId (the layer isn't known here)
t["LayeredSpellId"] = DynValue.NewTable(layered);
t["Enchantment"] = ChEnchantmentTable(s, spellId, expiry, serverNow, unixNow);
return DynValue.NewTable(t);
});
}
// The engine's enchantment events (API v70+; spell ids, layer stripped). They reach the
// plugin after AC applied the change, so the diff on the next tick reads the new state.
partial void CharacterOnEnchantmentAdded(uint spellId, double durationSeconds)
{
uint id = spellId & 0xFFFF;
if (durationSeconds > 0) _chEnchDuration[id] = durationSeconds;
if (_chEnchKnown) _chEnchEventAdds.Add(id);
_chEnchDirty = true;
}
partial void CharacterOnEnchantmentRemoved(uint enchantmentId) => _chEnchDirty = true;
// ── Combat mode ─────────────────────────────────────────────────────────
private int _chCombatMode = -1;
partial void CharacterOnCombatModeChange(int currentMode, int previousMode) =>
ChCombatModeChanged(currentMode, _chCombatMode > 0 ? _chCombatMode : previousMode);
private void ChCombatModeChanged(int currentMode, int previousMode)
{
if (currentMode == _chCombatMode) return; // already reported (engine event or the tick's poll)
_chCombatMode = currentMode;
FireAll("Character.OnCombatModeChanged", s =>
{
var t = new Table(s);
t["NewMode"] = (double)currentMode;
t["OldMode"] = (double)previousMode;
t["NewModeName"] = LuaEnums.CombatModeName(currentMode);
t["OldModeName"] = LuaEnums.CombatModeName(previousMode);
return DynValue.NewTable(t);
});
}
// ── Death ───────────────────────────────────────────────────────────────
private static readonly string[] DeathLineStarts =
{
"You have died", "You died", "You were killed", "You have been killed", "You've been killed", "You are dead",
};
partial void CharacterOnChatText(string text, int chatType)
{
if (GameState != "InGame" || text.Length > 200 || text.IndexOf('"') >= 0) return; // tells and chat quote their text
string line = text.Trim();
bool death = false;
foreach (string p in DeathLineStarts)
if (line.StartsWith(p, StringComparison.OrdinalIgnoreCase)) { death = true; break; }
if (!death && (line.EndsWith("killed you!", StringComparison.OrdinalIgnoreCase)
|| line.EndsWith("killed you.", StringComparison.OrdinalIgnoreCase)))
death = true;
if (!death) return;
long now = Environment.TickCount64;
_chDeathText = line;
_chDeathTextAt = now;
if (now - _chLastDeathAt >= ChDeathWindowMs) ChFireDeath(now, line);
}
partial void CharacterOnUpdateHealth(uint targetId, float ratio, uint current, uint max)
{
if (GameState != "InGame" || targetId == 0 || targetId != Host.GetPlayerId()) return;
long now = Environment.TickCount64;
if (max > 0 && current == 0 && now - _chBaselineAt >= ChLoginSettleMs) ChDeathSignal(now);
}
/// <summary>A non-chat death signal: fire a moment later, so a death line arriving meanwhile becomes the Text.</summary>
private void ChDeathSignal(long now)
{
if (now - _chLastDeathAt < ChDeathWindowMs || _chDeathPendingAt != 0) return;
_chDeathPendingAt = now + 1000;
}
private void ChFireDeath(long now, string text)
{
_chDeathPendingAt = 0;
_chLastDeathAt = now;
FireAll("Character.OnDeath", s =>
{
var t = new Table(s);
t["Text"] = text;
t["KillerId"] = 0.0; // UB's field; the killer isn't known here
return DynValue.NewTable(t);
});
}
}

View file

@ -0,0 +1,127 @@
using System;
using System.Collections.Generic;
using MoonSharp.Interpreter;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthLua;
/// <summary>
/// <c>game.Character.Trade</c> (UtilityBelt's Trade): the player-to-player trade window from
/// the engine's trade state (API v72), read live, and its events found by comparing each
/// tick's state with the last one: OnStarted {InitiatorId, PartnerId}, OnObjectAdded
/// {ObjectId, Side}, OnAccepted {AcceptorId}, OnDeclined {DeclinerId}, OnReset
/// {ResetterObjectId}, OnFailedToAddObject {ObjectId, Reason}, OnCompleted {PartnerId,
/// YourItemIds, PartnerItemIds}, OnEnded {Reason}. The trade actions are game.Actions'
/// (TradeAdd, TradeAccept, ...). On an engine without trade support IsOpen stays false and
/// nothing fires.
/// </summary>
public sealed partial class RynthLuaPlugin
{
private static readonly string[] TradeEventNames =
{
"OnStarted", "OnObjectAdded", "OnAccepted", "OnDeclined", "OnReset", "OnFailedToAddObject",
"OnCompleted", "OnEnded", "OnFailed",
};
private bool _trKnown;
private TradeState _tr;
private uint[] _trSelf = Array.Empty<uint>(), _trPartner = Array.Empty<uint>();
private DynValue CreateTradeTable(Script s, ScriptContext ctx)
{
var t = new Table(s);
foreach (string e in TradeEventNames)
t[e] = ctx.Event("Character.Trade." + e).CreateTable(s);
var mt = new Table(s);
mt["__index"] = DynValue.NewCallback((c, a) =>
{
string key = a.Count > 1 ? a[1].CastToString() ?? "" : "";
bool have = Host.TryGetTradeState(out TradeState st);
switch (key)
{
case "IsOpen": return DynValue.NewBoolean(have && st.IsOpen);
case "PartnerId": return DynValue.NewNumber(have && st.IsOpen ? st.PartnerId : 0);
case "YouAccepted": return DynValue.NewBoolean(have && st.IsOpen && st.YouAccepted);
case "PartnerAccepted": return DynValue.NewBoolean(have && st.IsOpen && st.PartnerAccepted);
case "YourItemIds": return IdList(s, have && st.IsOpen ? new List<uint>(Host.GetTradeItems(TradeSide.You)) : new List<uint>());
case "PartnerItemIds": return IdList(s, have && st.IsOpen ? new List<uint>(Host.GetTradeItems(TradeSide.Partner)) : new List<uint>());
default: return DynValue.Nil;
}
});
mt["__tostring"] = DynValue.NewCallback((c, a) =>
DynValue.NewString(Host.TryGetTradeState(out TradeState st) && st.IsOpen ? $"Trade with 0x{st.PartnerId:X8}" : "Trade (closed)"));
t.MetaTable = mt;
return DynValue.NewTable(t);
}
/// <summary>Every tick: what changed in the trade window since the last tick.</summary>
private void TradeTick()
{
if (!Host.HasTrade || !Host.TryGetTradeState(out TradeState st)) return;
if (!_trKnown)
{
_tr = st;
_trKnown = true;
if (st.IsOpen) { _trSelf = Host.GetTradeItems(TradeSide.You); _trPartner = Host.GetTradeItems(TradeSide.Partner); }
return;
}
TradeState old = _tr;
if (st.Sequence == old.Sequence && st.Generation == old.Generation && st.IsOpen == old.IsOpen
&& st.CompletedCount == old.CompletedCount && st.FailureCount == old.FailureCount)
return;
_tr = st;
uint[] oldSelf = _trSelf, oldPartner = _trPartner;
uint[] self = st.IsOpen ? Host.GetTradeItems(TradeSide.You) : Array.Empty<uint>();
uint[] partner = st.IsOpen ? Host.GetTradeItems(TradeSide.Partner) : Array.Empty<uint>();
if (st.Generation != old.Generation && st.IsOpen)
{
oldSelf = oldPartner = Array.Empty<uint>();
TradeFire("OnStarted", ("InitiatorId", st.InitiatorId), ("PartnerId", st.PartnerId));
}
foreach (uint id in self)
if (Array.IndexOf(oldSelf, id) < 0) TradeFire("OnObjectAdded", ("ObjectId", id), ("Side", 1u));
foreach (uint id in partner)
if (Array.IndexOf(oldPartner, id) < 0) TradeFire("OnObjectAdded", ("ObjectId", id), ("Side", 2u));
if (st.LastEventType == 0x0205 && st.Sequence != old.Sequence)
TradeFire("OnReset", ("ResetterObjectId", st.LastResetBy));
if (st.PartnerAcceptCount > old.PartnerAcceptCount)
TradeFire("OnAccepted", ("AcceptorId", st.PartnerId != 0 ? st.PartnerId : old.PartnerId));
if (st.YouAccepted && !old.YouAccepted)
TradeFire("OnAccepted", ("AcceptorId", Host.GetPlayerId()));
if (st.LastEventType == 0x0203 && st.Sequence != old.Sequence)
TradeFire("OnDeclined", ("DeclinerId", st.LastDeclinedBy));
if (st.FailureCount > old.FailureCount)
TradeFire("OnFailedToAddObject", ("ObjectId", st.LastFailureItemId), ("Reason", st.LastFailureReason));
if (st.CompletedCount > old.CompletedCount)
{
uint[] yours = self.Length > 0 ? self : _trSelf, theirs = partner.Length > 0 ? partner : _trPartner;
uint who = old.PartnerId;
FireAll("Character.Trade.OnCompleted", s =>
{
var t = new Table(s);
t["PartnerId"] = (double)who;
t["YourItemIds"] = IdList(s, new List<uint>(yours));
t["PartnerItemIds"] = IdList(s, new List<uint>(theirs));
return DynValue.NewTable(t);
});
}
if (old.IsOpen && !st.IsOpen)
TradeFire("OnEnded", ("Reason", st.LastCloseReason));
if (st.IsOpen || self.Length > 0 || partner.Length > 0) { _trSelf = self; _trPartner = partner; }
if (!st.IsOpen) { _trSelf = Array.Empty<uint>(); _trPartner = Array.Empty<uint>(); }
}
private void TradeFire(string evt, params (string Key, uint Value)[] fields)
{
FireAll("Character.Trade." + evt, s =>
{
var t = new Table(s);
foreach (var (k, v) in fields) t[k] = (double)v;
return DynValue.NewTable(t);
});
}
}

View file

@ -0,0 +1,572 @@
using System;
using System.Buffers;
using System.Collections.Generic;
using MoonSharp.Interpreter;
namespace RynthCore.Plugin.RynthLua;
/// <summary>
/// game.World (UtilityBelt's World): object lookup and search, the selected object, the
/// player's inventory, and the world events (objects created/released, chat, tells,
/// selection). WorldObject properties live in GameWorldObject.cs.
///
/// The SDK has no "every object the client knows" call, so World keeps its own set of
/// known ids: OnCreateObject/OnDeleteObject, the player's inventory (seeded after login,
/// and after a hot reload), and any id a script or the selection proves exists.
/// Everything runs on the plugin pump thread; the SDK reads used here are served from the
/// engine's snapshots (names, types, positions) or guarded reads (ownership, bitfield).
/// </summary>
public sealed partial class RynthLuaPlugin
{
private readonly HashSet<uint> _worldKnown = new();
/// <summary>Ids released recently (id → when): the engine's name snapshot can lag a delete.</summary>
private readonly Dictionary<uint, long> _worldReleased = new();
private bool _worldSeedPending = true; // true at load too: a hot reload mid-session seeds the inventory
private int _worldSeedTries;
private long _worldNextSeedAt;
private long _worldNextPruneAt;
private long _worldNextSnapshotAt;
private int _worldChangeSeq; // bumped on create/delete: invalidates the inventory cache
private readonly uint[] _worldContentsBuf = new uint[1024];
private uint[]? _worldInventoryCache;
private long _worldInventoryCacheTick = -1;
private int _worldInventoryCacheSeq = -1;
private const long WorldReleasedKeepMs = 10_000;
private const int WorldMaxSeedTries = 15;
// ── Lifecycle ───────────────────────────────────────────────────────────
partial void WorldOnLogin()
{
WorldReset();
_worldSeedPending = true;
}
partial void WorldOnLogout()
{
WorldReset();
_worldSeedPending = false;
}
private void WorldReset()
{
_worldKnown.Clear();
_worldReleased.Clear();
_worldClass.Clear();
_worldInventoryCache = null;
_worldSeedTries = 0;
_worldNextSeedAt = 0;
_worldChangeSeq++;
}
partial void WorldTick()
{
long now = Environment.TickCount64;
// Seed the known set with the player and everything they carry. Retried: right
// after login the engine's object snapshot may not be warm yet.
if (_worldSeedPending && now >= _worldNextSeedAt)
{
_worldNextSeedAt = now + 1000;
uint pid = Host.GetPlayerId();
if (pid != 0)
{
_worldKnown.Add(pid);
uint[] inv = WorldInventoryIds();
foreach (uint id in inv) _worldKnown.Add(id);
if (inv.Length > 0 || ++_worldSeedTries >= WorldMaxSeedTries) _worldSeedPending = false;
}
}
// Engine v69+: pick up everything in the client's object table, so objects that
// existed before this plugin loaded (hot reload, late start) are found too.
if (now >= _worldNextSnapshotAt && Host.HasGetLiveObjectIds && Host.GetPlayerId() != 0)
{
_worldNextSnapshotAt = now + 1000;
int before = _worldKnown.Count;
foreach (uint id in Host.GetLiveObjectIds())
if (!_worldReleased.ContainsKey(id)) _worldKnown.Add(id);
if (_worldKnown.Count != before) _worldChangeSeq++;
}
WorldPollPositions();
WorldPollOpenContainer();
if (now >= _worldNextPruneAt && _worldReleased.Count > 0)
{
_worldNextPruneAt = now + 2000;
List<uint>? old = null;
foreach (var kv in _worldReleased)
if (now - kv.Value > WorldReleasedKeepMs) (old ??= new()).Add(kv.Key);
if (old != null)
foreach (uint id in old) _worldReleased.Remove(id);
}
}
// ── Engine events ───────────────────────────────────────────────────────
partial void WorldOnCreateObject(uint objectId)
{
if (objectId == 0) return;
_worldKnown.Add(objectId);
_worldReleased.Remove(objectId);
_worldClass.Remove(objectId); // ids get reused: classify the new object afresh
_worldChangeSeq++;
FireWorld("World.OnObjectCreated", (s, ctx) =>
{
var t = new Table(s);
t["ObjectId"] = (double)objectId;
t["Object"] = WrapObject(s, ctx, objectId);
return DynValue.NewTable(t);
});
}
partial void WorldOnDeleteObject(uint objectId)
{
if (objectId == 0) return;
_worldKnown.Remove(objectId);
_worldClass.Remove(objectId);
_worldReleased[objectId] = Environment.TickCount64;
_worldChangeSeq++;
FireAll("World.OnObjectReleased", s =>
{
var t = new Table(s);
t["ObjectId"] = (double)objectId;
return DynValue.NewTable(t);
});
WorldFireDestroyed(objectId);
}
partial void WorldOnChatText(string text, int chatType)
{
string message = text.TrimEnd('\r', '\n');
ChatKind kind = ClassifyChat(message, chatType, out int room, out string senderName, out uint senderId, out string body);
// UB's ChatEventArgs: SenderId, SenderName, Message, Room (ChatChannel), Type
// (ChatMessageType), Eat. Incoming lines can't be eaten here (the engine hands them
// over after AC showed them), so Eat is always false.
DynValue Args(Script s, string msg)
{
var t = new Table(s);
t["Message"] = msg;
t["Type"] = (double)chatType;
t["SenderName"] = senderName;
t["SenderId"] = (double)senderId;
t["Room"] = (double)room;
t["Eat"] = false;
return DynValue.NewTable(t);
}
FireAll("World.OnChatText", s => Args(s, message));
string? specific = kind switch
{
ChatKind.Tell => "World.OnTell",
ChatKind.Local => "World.OnLocalMessage",
ChatKind.Channel => "World.OnChannelMessage",
ChatKind.Fellow => "World.OnFellowMessage",
ChatKind.Emote => "World.OnEmote",
_ => null,
};
if (specific != null) FireAll(specific, s => Args(s, kind == ChatKind.Emote ? message : body));
}
partial void WorldOnSelected(uint currentId, uint previousId)
{
if (currentId != 0)
{
_worldKnown.Add(currentId);
_worldReleased.Remove(currentId);
}
FireWorld("World.OnSelected", (s, ctx) =>
{
var t = new Table(s);
t["ObjectId"] = (double)currentId;
t["PreviousId"] = (double)previousId;
t["Object"] = WrapObject(s, ctx, currentId);
return DynValue.NewTable(t);
});
}
/// <summary>
/// Like FireAll, for args that hold WorldObjects (WrapObject needs the script's context).
/// Cheap when nobody listens: the scripts are only copied once one has a handler.
/// </summary>
private void FireWorld(string key, Func<Script, ScriptContext, DynValue> makeArgs)
{
bool any = false;
foreach (var c in _scripts.Values)
if (c.HasHandlers(key)) { any = true; break; }
if (!any) return;
foreach (var ctx in new List<ScriptContext>(_scripts.Values))
if (ctx.Host.Loaded && ctx.HasHandlers(key)) ctx.Fire(key, s => makeArgs(s, ctx));
}
/// <summary>
/// "Bob tells you, \"hi\"" or "Bob says, \"hi\"" → sender and message. AC's tell lines
/// may carry a name link, "&lt;Tell:IIDString:1342177281:Bob&gt;Bob&lt;\Tell&gt;", which gives the id too.
/// </summary>
internal static void ParseChatSender(string line, out string senderName, out uint senderId, out string body, out bool isTell)
{
senderName = string.Empty;
senderId = 0;
body = line;
isTell = false;
const string tellMark = " tells you, \"";
const string sayMark = " says, \"";
int at = line.IndexOf(tellMark, StringComparison.Ordinal);
int markLen = tellMark.Length;
if (at > 0) isTell = true;
else
{
at = line.IndexOf(sayMark, StringComparison.Ordinal);
markLen = sayMark.Length;
if (at <= 0) return;
}
string who = line[..at];
body = line[(at + markLen)..];
if (body.EndsWith('"')) body = body[..^1];
// <Tell:IIDString:ID:NAME>DISPLAY<\Tell>
if (who.StartsWith("<Tell:", StringComparison.Ordinal))
{
int close = who.IndexOf('>');
if (close > 0)
{
string[] parts = who[1..close].Split(':');
if (parts.Length >= 3) uint.TryParse(parts[2], out senderId);
int end = who.IndexOf("<\\Tell>", close, StringComparison.Ordinal);
who = end > close ? who[(close + 1)..end] : (parts.Length >= 4 ? parts[3] : who[(close + 1)..]);
}
}
senderName = who.Trim();
}
// ── game.World ──────────────────────────────────────────────────────────
partial void RegisterWorldApi(Script s, ScriptContext ctx, Table game)
{
var world = new Table(s);
world["OnObjectCreated"] = ctx.Event("World.OnObjectCreated").CreateTable(s);
world["OnObjectReleased"] = ctx.Event("World.OnObjectReleased").CreateTable(s);
world["OnChatText"] = ctx.Event("World.OnChatText").CreateTable(s);
world["OnTell"] = ctx.Event("World.OnTell").CreateTable(s);
world["OnLocalMessage"] = ctx.Event("World.OnLocalMessage").CreateTable(s);
world["OnChannelMessage"] = ctx.Event("World.OnChannelMessage").CreateTable(s);
world["OnFellowMessage"] = ctx.Event("World.OnFellowMessage").CreateTable(s);
world["OnEmote"] = ctx.Event("World.OnEmote").CreateTable(s);
world["OnChatInput"] = ctx.Event("World.OnChatInput").CreateTable(s);
world["OnContainerOpened"] = ctx.Event("World.OnContainerOpened").CreateTable(s);
world["OnContainerClosed"] = ctx.Event("World.OnContainerClosed").CreateTable(s);
world["OnTick"] = ctx.Event("World.OnTick").CreateTable(s);
world["Vendor"] = CreateVendorTable(s, ctx);
ctx.OnStop.Add(() =>
{
foreach (var kv in _worldEatenCommands.ToArray())
if (kv.Value.Equals(ctx.Name, StringComparison.OrdinalIgnoreCase)) _worldEatenCommands.TryRemove(kv.Key, out _);
});
DynValue selected = ctx.Event("World.OnSelected").CreateTable(s);
world["OnSelected"] = selected;
world["OnObjectSelected"] = selected; // UtilityBelt's name for the same event
world["Get"] = DynValue.NewCallback((c, a) =>
{
uint id = WorldIdArg(LuaArgs.At(LuaArgs.Of(a, world), 0), "Get(id)");
return WorldExists(id) ? WrapObject(s, ctx, id) : DynValue.Nil;
});
// UB: local ok, wo = game.World.TryGet(id)
world["TryGet"] = DynValue.NewCallback((c, a) =>
{
uint id = WorldIdArg(LuaArgs.At(LuaArgs.Of(a, world), 0), "TryGet(id)");
return WorldExists(id)
? DynValue.NewTuple(DynValue.True, WrapObject(s, ctx, id))
: DynValue.NewTuple(DynValue.False, DynValue.Nil);
});
world["Exists"] = DynValue.NewCallback((c, a) =>
DynValue.NewBoolean(WorldExists(WorldIdArg(LuaArgs.At(LuaArgs.Of(a, world), 0), "Exists(id)"))));
world["GetAll"] = DynValue.NewCallback((c, a) =>
{
var filter = WorldFilter.Parse(LuaArgs.At(LuaArgs.Of(a, world), 0), "GetAll");
return WorldCollect(s, ctx, WorldKnownIds(), filter, landscapeOnly: false);
});
world["GetLandscape"] = DynValue.NewCallback((c, a) =>
{
var filter = WorldFilter.Parse(LuaArgs.At(LuaArgs.Of(a, world), 0), "GetLandscape");
return WorldCollect(s, ctx, WorldKnownIds(), filter, landscapeOnly: true);
});
world["GetInventory"] = DynValue.NewCallback((c, a) =>
{
var filter = WorldFilter.Parse(LuaArgs.At(LuaArgs.Of(a, world), 0), "GetInventory");
uint[] ids = WorldInventoryIds();
return WorldCollect(s, ctx, new ArraySegment<uint>(ids), filter, landscapeOnly: false, pooled: false);
});
// GetNearest(filter [, DistanceType]): DistanceType.T2D (0) ignores height, T3D (1, the default) doesn't.
world["GetNearest"] = DynValue.NewCallback((c, a) =>
{
var args = LuaArgs.Of(a, world);
var filter = WorldFilter.Parse(LuaArgs.At(args, 0), "GetNearest");
DynValue dt = LuaArgs.At(args, 1);
bool flat = !dt.IsNil() && LuaArgs.Num(dt, 1) == 0;
return WorldNearest(s, ctx, filter, flat);
});
var mt = new Table(s);
mt["__index"] = DynValue.NewCallback((c, a) =>
{
DynValue key = a.Count > 1 ? a[1] : DynValue.Nil;
if (key.Type == DataType.Number) // game.World[id], like UB's indexer
{
uint id = (uint)key.Number;
return WorldExists(id) ? WrapObject(s, ctx, id) : DynValue.Nil;
}
switch (key.CastToString())
{
case "Selected":
uint sel = Host.GetSelectedItemId();
return sel != 0 ? WrapObject(s, ctx, sel) : DynValue.Nil;
case "OpenContainer":
uint open = Host.HasGetGroundContainerId ? Host.GetGroundContainerId() : 0;
return open != 0 ? WrapObject(s, ctx, open) : DynValue.Nil;
default:
return DynValue.Nil;
}
});
mt["__tostring"] = DynValue.NewCallback((c, a) => DynValue.NewString($"game.World ({_worldKnown.Count} known objects)"));
world.MetaTable = mt;
game["World"] = DynValue.NewTable(world);
}
private static uint WorldIdArg(DynValue v, string what)
{
uint id = LuaArgs.Id(v);
if (id == 0 && v.Type != DataType.Number && v.Type != DataType.Nil)
{
// "12345" or "0x80001234" typed by hand
string t = (v.CastToString() ?? "").Trim();
if (t.StartsWith("0x", StringComparison.OrdinalIgnoreCase))
uint.TryParse(t[2..], System.Globalization.NumberStyles.HexNumber, null, out id);
else
uint.TryParse(t, out id);
if (id == 0) throw new ScriptRuntimeException($"World.{what}: '{t}' isn't an object id");
}
return id;
}
/// <summary>True when the client knows object <paramref name="id"/> (a lazy lookup adds it to the known set).</summary>
internal bool WorldExists(uint id)
{
if (id == 0) return false;
if (_worldKnown.Contains(id)) return true;
if (_worldReleased.ContainsKey(id)) return false;
if (Host.TryGetObjectName(id, out _) || Host.TryGetObjectPosition(id, out _, out _, out _, out _))
{
_worldKnown.Add(id);
return true;
}
return false;
}
/// <summary>Known objects whose wielder is <paramref name="wielder"/> (worn and wielded items).</summary>
internal List<uint> WorldWieldedIds(uint wielder)
{
var list = new List<uint>();
if (wielder == 0 || !Host.HasGetObjectOwnershipInfo) return list;
foreach (uint id in _worldKnown)
if (id != wielder && Host.TryGetObjectOwnershipInfo(id, out _, out uint w, out _) && w == wielder)
list.Add(id);
return list;
}
/// <summary>A pooled copy of the known ids (a filter function may create or release objects meanwhile).</summary>
private ArraySegment<uint> WorldKnownIds()
{
uint[] ids = ArrayPool<uint>.Shared.Rent(Math.Max(1, _worldKnown.Count));
_worldKnown.CopyTo(ids);
return new ArraySegment<uint>(ids, 0, _worldKnown.Count);
}
/// <summary>
/// Everything the player owns: the main pack, side packs and their contents, and what
/// they wield. Cached for the rest of the tick unless an object is created or released.
/// </summary>
internal uint[] WorldInventoryIds()
{
if (_worldInventoryCache != null && _worldInventoryCacheTick == LastTick && _worldInventoryCacheSeq == _worldChangeSeq)
return _worldInventoryCache;
uint pid = Host.GetPlayerId();
if (pid == 0 || !Host.HasGetContainerContents) return Array.Empty<uint>();
var ids = new List<uint>(128);
List<uint>? packs = null;
int n = Host.GetContainerContents(pid, _worldContentsBuf);
for (int i = 0; i < n; i++)
{
uint id = _worldContentsBuf[i];
ids.Add(id);
if (Host.TryGetItemType(id, out uint type) && (type & ItemTypeContainer) != 0) (packs ??= new()).Add(id);
}
if (packs != null)
foreach (uint pack in packs)
{
int m = Host.GetContainerContents(pack, _worldContentsBuf);
for (int i = 0; i < m; i++) ids.Add(_worldContentsBuf[i]);
}
// Worn and wielded items aren't in any container list.
var inPacks = new HashSet<uint>(ids);
foreach (uint id in WorldWieldedIds(pid))
if (inPacks.Add(id)) ids.Add(id);
_worldInventoryCache = ids.ToArray();
_worldInventoryCacheTick = LastTick;
_worldInventoryCacheSeq = _worldChangeSeq;
return _worldInventoryCache;
}
/// <summary>
/// A world object lying in the world (not the player, not in a container, not wielded).
/// Position first: pack items have none, and it comes from the engine's snapshot.
/// </summary>
private bool WorldIsLandscape(uint id, uint playerId)
{
if (id == playerId) return false;
if (!Host.TryGetObjectPosition(id, out _, out _, out _, out _)) return false;
if (Host.TryGetObjectOwnershipInfo(id, out uint container, out uint wielder, out _))
return container == 0 && wielder == 0;
return true;
}
private DynValue WorldCollect(Script s, ScriptContext ctx, ArraySegment<uint> ids, WorldFilter filter, bool landscapeOnly, bool pooled = true)
{
var result = new Table(s);
try
{
uint pid = landscapeOnly ? Host.GetPlayerId() : 0;
int n = 0;
foreach (uint id in ids)
{
if (!filter.MatchesCheap(this, id)) continue;
if (landscapeOnly && !WorldIsLandscape(id, pid)) continue;
DynValue wo = WrapObject(s, ctx, id);
if (!filter.MatchesFunction(s, wo)) continue;
result.Set(++n, wo);
}
}
finally
{
if (pooled && ids.Array != null) ArrayPool<uint>.Shared.Return(ids.Array);
}
return DynValue.NewTable(result);
}
/// <summary>The nearest landscape object matching the filter; a function filter is tried nearest-first.</summary>
private DynValue WorldNearest(Script s, ScriptContext ctx, WorldFilter filter, bool flat)
{
uint pid = Host.GetPlayerId();
if (!WorldTryGetPosition(pid, out WorldPos me)) return DynValue.Nil;
var candidates = new List<(uint Id, double Dist)>();
ArraySegment<uint> ids = WorldKnownIds();
try
{
foreach (uint id in ids)
{
if (id == pid || !filter.MatchesCheap(this, id)) continue;
if (!WorldTryGetPosition(id, out WorldPos p)) continue;
if (Host.TryGetObjectOwnershipInfo(id, out uint container, out uint wielder, out _) && (container != 0 || wielder != 0))
continue;
double d = flat ? me.DistanceTo2D(p) : me.DistanceTo(p);
if (double.IsFinite(d)) candidates.Add((id, d));
}
}
finally
{
if (ids.Array != null) ArrayPool<uint>.Shared.Return(ids.Array);
}
candidates.Sort((x, y) => x.Dist.CompareTo(y.Dist));
foreach (var (id, _) in candidates)
{
DynValue wo = WrapObject(s, ctx, id);
if (filter.MatchesFunction(s, wo)) return wo;
}
return DynValue.Nil;
}
/// <summary>
/// A World filter: nothing, a name substring, an ObjectClass (number, or its exact name
/// such as "Monster"), an ObjectType (UB's typed value: every flag must be set), or a Lua
/// function(wo) → bool.
/// </summary>
private readonly struct WorldFilter
{
private readonly string? _name;
private readonly int _class;
private readonly DynValue? _fn;
private readonly uint _type;
private WorldFilter(string? name, int cls, DynValue? fn, uint type = 0)
{
_name = name;
_class = cls;
_fn = fn;
_type = type;
}
public static WorldFilter Parse(DynValue v, string what)
{
switch (v.Type)
{
case DataType.Nil:
case DataType.Void:
return new WorldFilter(null, -1, null);
case DataType.Number:
return new WorldFilter(null, (int)v.Number, null);
case DataType.String:
{
string text = v.String;
int cls = Array.IndexOf(LuaEnums.ObjectClass, text); // exact, case-sensitive: "Monster", "Portal"
return cls >= 0 ? new WorldFilter(null, cls, null) : new WorldFilter(text, -1, null);
}
case DataType.Function:
case DataType.ClrFunction:
return new WorldFilter(null, -1, v);
case DataType.Table when LuaEnumValues.TryRead(v, out string en, out long flags) && en == "ObjectType":
if (flags == 0) throw new ScriptRuntimeException($"World.{what}(ObjectType): pick at least one ObjectType flag");
return new WorldFilter(null, -1, null, (uint)flags);
default:
throw new ScriptRuntimeException(
$"World.{what}(filter): the filter is a name, an ObjectClass, an ObjectType or a function(wo) returning true/false, not a {v.Type.ToString().ToLowerInvariant()}");
}
}
/// <summary>The name and class parts (no Lua call).</summary>
public bool MatchesCheap(RynthLuaPlugin p, uint id)
{
if (_class >= 0 && p.WorldClassOf(id) != _class) return false;
if (_type != 0 && (!p.Host.TryGetItemType(id, out uint t) || (t & _type) != _type)) return false;
if (_name != null)
{
if (!p.Host.TryGetObjectName(id, out string n) || n.IndexOf(_name, StringComparison.OrdinalIgnoreCase) < 0)
return false;
}
return true;
}
public bool MatchesFunction(Script s, DynValue wo)
{
if (_fn == null) return true;
return s.Call(_fn, wo).CastToBool();
}
}
}

View file

@ -0,0 +1,235 @@
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using MoonSharp.Interpreter;
namespace RynthCore.Plugin.RynthLua;
/// <summary>
/// game.World's UtilityBelt extras: the chat events by kind (tell, local, channel, fellow,
/// emote), OnChatInput, the open container and its events, and the Vendor object.
/// </summary>
public sealed partial class RynthLuaPlugin
{
// ── Chat lines by kind ──────────────────────────────────────────────────
internal enum ChatKind { Other, Tell, Local, Channel, Fellow, Emote }
/// <summary>"[Room] ..." prefixes → UB's ChatChannel numbers.</summary>
private static readonly (string Tag, int Room)[] ChatRooms =
{
("Allegiance", 1), ("General", 2), ("Trade", 3), ("LFG", 4), ("Roleplay", 5), ("Olthoi", 6),
("Society", 7), ("Celestial Hand", 8), ("Eldrytch Web", 9), ("Radiant Blood", 10),
};
private const int ChatTypeSpeech = 2, ChatTypeTell = 3, ChatTypeEmote = 12;
/// <summary>
/// What kind of line this is, from AC's text: "[General] Bob says, \"...\"" is a channel
/// line (Room from the tag), "[Fellowship] ..." a fellowship line, "Bob tells you, ..."
/// (type Tell) a tell, "Bob says, ..." (type Speech) a local message, and a type Emote line
/// an emote. SenderName / SenderId are "" / 0 when the line names nobody.
/// </summary>
internal static ChatKind ClassifyChat(string line, int chatType, out int room, out string senderName, out uint senderId, out string body)
{
room = 0;
string rest = line;
string? tag = null;
if (line.StartsWith('['))
{
int close = line.IndexOf(']');
if (close > 1)
{
tag = line[1..close];
rest = line[(close + 1)..].TrimStart();
}
}
ParseChatSender(rest, out senderName, out senderId, out body, out bool isTell);
if (tag != null)
{
if (tag.Equals("Fellowship", StringComparison.OrdinalIgnoreCase)) return ChatKind.Fellow;
foreach (var (t, r) in ChatRooms)
if (t.Equals(tag, StringComparison.OrdinalIgnoreCase)) { room = r; return ChatKind.Channel; }
return ChatKind.Other;
}
if (isTell && chatType == ChatTypeTell) return ChatKind.Tell; // anything else only looks like one
if (!isTell && senderName.Length > 0 && chatType == ChatTypeSpeech) return ChatKind.Local;
if (chatType == ChatTypeEmote) return ChatKind.Emote;
return ChatKind.Other;
}
// ── World.OnChatInput ───────────────────────────────────────────────────
// AC hands typed lines to plugins on its own thread, where Lua can't run, so handlers see
// a line on the next tick and can't stop that line any more. What they can do, the UB way,
// is set e.Eat = true for a line starting with "/word": from then on RynthLua eats every
// line starting with that word as it is typed (until the script stops), and handlers get
// those lines with Eat already true. game.RegisterCommand eats from the first line.
private readonly ConcurrentQueue<(string Text, bool Eaten)> _worldChatInputs = new();
/// <summary>"/word" → the script whose handler ate it.</summary>
private readonly ConcurrentDictionary<string, string> _worldEatenCommands = new(StringComparer.OrdinalIgnoreCase);
private readonly List<(Table Args, ScriptContext Ctx, string Word, long Until)> _worldChatInputWatch = new();
private static string CommandWord(string line)
{
if (!line.StartsWith('/')) return string.Empty;
int sp = line.IndexOf(' ');
return sp < 0 ? line : line[..sp];
}
/// <summary>AC's thread: queue the line for OnChatInput; true when a learned command eats it.</summary>
private bool WorldQueueChatInput(string line, bool alreadyEaten)
{
bool eat = !alreadyEaten && !_worldEatenCommands.IsEmpty && CommandWord(line) is { Length: > 0 } w && _worldEatenCommands.ContainsKey(w);
_worldChatInputs.Enqueue((line, alreadyEaten || eat)); // drained every tick
return eat;
}
/// <summary>Pump thread, every tick: deliver queued input lines, learn eaten commands.</summary>
private void WorldTickChatInput()
{
long now = Environment.TickCount64;
for (int i = _worldChatInputWatch.Count - 1; i >= 0; i--)
{
var (args, ctx, word, until) = _worldChatInputWatch[i];
if (args.Get("Eat").CastToBool() && word.Length > 0 && ctx.Host.Loaded)
{
_worldEatenCommands[word] = ctx.Name;
_worldChatInputWatch.RemoveAt(i);
}
else if (now > until || !ctx.Host.Loaded) _worldChatInputWatch.RemoveAt(i);
}
while (_worldChatInputs.TryDequeue(out var input))
{
string word = CommandWord(input.Text);
foreach (var ctx in new List<ScriptContext>(_scripts.Values))
{
if (!ctx.Host.Loaded || !ctx.HasHandlers("World.OnChatInput")) continue;
ctx.Fire("World.OnChatInput", s =>
{
var t = new Table(s);
t["Text"] = input.Text;
t["Eat"] = input.Eaten;
if (!input.Eaten && word.Length > 0) _worldChatInputWatch.Add((t, ctx, word, now + 3000));
return DynValue.NewTable(t);
});
}
}
}
// ── The open container ──────────────────────────────────────────────────
private uint _worldOpenContainer;
/// <summary>The engine's view/stop-viewing events, and every tick's check of the ground container (whichever is first).</summary>
private void WorldSetOpenContainer(uint id)
{
if (id == _worldOpenContainer) return;
uint old = _worldOpenContainer;
_worldOpenContainer = id;
if (old != 0)
FireWorld("World.OnContainerClosed", (s, ctx) =>
{
var t = new Table(s);
t["Container"] = WrapObject(s, ctx, old);
return DynValue.NewTable(t);
});
if (id != 0)
{
_worldKnown.Add(id);
FireWorld("World.OnContainerOpened", (s, ctx) =>
{
var t = new Table(s);
t["Container"] = WrapObject(s, ctx, id);
return DynValue.NewTable(t);
});
}
}
public override void OnViewObjectContents(uint objectId)
{
// Only containers on the ground count (the engine also reports the player's own packs).
if (objectId != 0 && objectId == (Host.HasGetGroundContainerId ? Host.GetGroundContainerId() : objectId))
WorldSetOpenContainer(objectId);
}
public override void OnStopViewingObjectContents(uint objectId)
{
if (objectId == _worldOpenContainer) WorldSetOpenContainer(0);
}
private void WorldPollOpenContainer()
{
if (!Host.HasGetGroundContainerId || GameState != "InGame") return;
WorldSetOpenContainer(Host.GetGroundContainerId());
}
// ── game.World.Vendor ───────────────────────────────────────────────────
partial void WorldOnVendor(uint vendorId, bool open)
{
if (!open) { Cart.ClearBuy(); Cart.ClearSell(); }
FireAll(open ? "World.Vendor.OnOpened" : "World.Vendor.OnClosed", s => DynValue.NewTable(new Table(s)));
}
/// <summary>
/// UB's Vendor: IsOpen, VendorId, Name, MinBuyValue, MaxBuyValue, Magic, BuyPriceModifier,
/// SellPriceModifier, CurrencyType, CurrencyName, PlayerCurrencyAmount, Category (ObjectType),
/// Items ({ObjectId, Name, Amount (-1 = unlimited), UnitPrice, StackSize, MaxStackSize,
/// ObjectType}), OnOpened, OnClosed. Read live from the engine's vendor snapshot (API v67).
/// </summary>
private DynValue CreateVendorTable(Script s, ScriptContext ctx)
{
var v = new Table(s);
v["OnOpened"] = ctx.Event("World.Vendor.OnOpened").CreateTable(s);
v["OnClosed"] = ctx.Event("World.Vendor.OnClosed").CreateTable(s);
var mt = new Table(s);
mt["__index"] = DynValue.NewCallback((c, a) =>
{
string key = a.Count > 1 ? a[1].CastToString() ?? "" : "";
bool open = Host.TryGetVendorInfo(out var info);
switch (key)
{
case "IsOpen": return DynValue.NewBoolean(open);
case "VendorId": return DynValue.NewNumber(open ? info.VendorId : 0);
case "Name": return DynValue.NewString(open ? info.Name : string.Empty);
case "MinBuyValue": return DynValue.NewNumber(open ? info.MinValue : 0);
case "MaxBuyValue": return DynValue.NewNumber(open ? info.MaxValue : 0);
case "Magic": return DynValue.NewNumber(open && info.DealsMagic ? 1 : 0);
case "BuyPriceModifier": return DynValue.NewNumber(open ? info.BuyRate : 0);
case "SellPriceModifier": return DynValue.NewNumber(open ? info.SellRate : 0);
case "CurrencyType": return DynValue.NewNumber(open ? info.AltCurrencyWcid : 0);
case "CurrencyName":
return DynValue.NewString(!open ? string.Empty : info.UsesAltCurrency ? info.AltCurrencyName : "Pyreal");
case "PlayerCurrencyAmount":
return DynValue.NewNumber(!open ? 0 : info.UsesAltCurrency ? Math.Max(0, info.AltCurrencyHave) : Math.Max(0, info.PlayerCoins));
case "Category": return LuaEnumValues.Get(s, "ObjectType", open ? info.ItemTypes : 0);
case "Items":
{
var list = new Table(s);
int i = 0;
if (open)
foreach (var item in Host.GetVendorItems())
{
var t = new Table(s);
t["ObjectId"] = (double)item.ObjectId;
t["Name"] = item.Name;
t["Amount"] = (double)item.Amount;
t["UnitPrice"] = (double)item.UnitPrice;
t["StackSize"] = (double)item.StackSize;
t["MaxStackSize"] = (double)item.MaxStackSize;
t["ObjectType"] = LuaEnumValues.Get(s, "ObjectType", item.ItemType);
list.Set(++i, DynValue.NewTable(t));
}
return LuaLists.Wrap(s, list);
}
default: return DynValue.Nil;
}
});
mt["__tostring"] = DynValue.NewCallback((c, a) =>
DynValue.NewString(Host.TryGetVendorInfo(out var info) ? $"Vendor {info.Name} (0x{info.VendorId:X8})" : "Vendor (closed)"));
v.MetaTable = mt;
return DynValue.NewTable(v);
}
}

View file

@ -0,0 +1,806 @@
using System;
using System.Collections.Generic;
using MoonSharp.Interpreter;
namespace RynthCore.Plugin.RynthLua;
/// <summary>
/// WorldObject properties (UtilityBelt's WorldObject): WrapObject makes the table, World gives
/// it one shared metatable per script whose <c>__index</c> reads every property live through
/// the SDK, plus <c>__tostring</c> and <c>__eq</c> (same Id). Methods (IntValue, DistanceTo,
/// Items, ...) are bound on first use and stored on the object, so wrapping hundreds of
/// objects in GetAll costs one table each. Action methods (Use, Give, ...) are Actions'.
/// </summary>
public sealed partial class RynthLuaPlugin
{
/// <summary>The WorldObject metatable of each running script's Lua state.</summary>
private readonly Dictionary<Script, Table> _worldObjectMeta = new();
/// <summary>ObjectClass per id, once it was read from reliable data (see WorldClassify).</summary>
private readonly Dictionary<uint, int> _worldClass = new();
// AC ITEM_TYPE flags (WorldObject.ObjectType)
private const uint ItemTypeMeleeWeapon = 0x00000001;
private const uint ItemTypeArmor = 0x00000002;
private const uint ItemTypeClothing = 0x00000004;
private const uint ItemTypeJewelry = 0x00000008;
private const uint ItemTypeCreature = 0x00000010;
private const uint ItemTypeFood = 0x00000020;
private const uint ItemTypeMoney = 0x00000040;
private const uint ItemTypeMisc = 0x00000080;
private const uint ItemTypeMissileWeapon = 0x00000100;
private const uint ItemTypeContainer = 0x00000200;
private const uint ItemTypeGem = 0x00000800;
private const uint ItemTypeSpellComponents = 0x00001000;
private const uint ItemTypeWritable = 0x00002000;
private const uint ItemTypeKey = 0x00004000;
private const uint ItemTypeCaster = 0x00008000;
private const uint ItemTypePortal = 0x00010000;
private const uint ItemTypePromissoryNote = 0x00040000;
private const uint ItemTypeManaStone = 0x00080000;
private const uint ItemTypeService = 0x00100000;
private const uint ItemTypeCraftCookingBase = 0x00400000;
private const uint ItemTypeCraftAlchemyBase = 0x00800000;
private const uint ItemTypeCraftFletchingBase = 0x02000000;
private const uint ItemTypeCraftAlchemyIntermediate = 0x04000000;
private const uint ItemTypeCraftFletchingIntermediate = 0x08000000;
private const uint ItemTypeLifeStone = 0x10000000;
private const uint ItemTypeTinkeringTool = 0x20000000;
private const uint ItemTypeTinkeringMaterial = 0x40000000;
// PublicWeenieDesc._bitfield (ObjectDescriptionFlag)
private const uint BfPlayer = 0x8;
private const uint BfAttackable = 0x10;
private const uint BfVendor = 0x200;
private const uint BfDoor = 0x1000;
private const uint BfCorpse = 0x2000;
private const uint BfLifestone = 0x4000;
private const uint BfFood = 0x8000;
private const uint BfHealer = 0x10000;
private const uint BfLockpick = 0x20000;
private const uint BfPortal = 0x40000;
// STypeInt ids behind the named properties
private const uint IntBurden = 5; // ENCUMB_VAL_INT
private const uint IntCurrentWieldedLocation = 10;
private const uint IntStackSize = 12;
private const uint IntValueProp = 19;
partial void DecorateObject(Script s, ScriptContext ctx, uint id, Table obj)
{
obj.MetaTable = WorldObjectMeta(s, ctx);
}
private Table WorldObjectMeta(Script s, ScriptContext ctx)
{
if (_worldObjectMeta.TryGetValue(s, out Table? mt)) return mt;
mt = new Table(s);
mt["__index"] = DynValue.NewCallback((c, a) =>
{
if (a.Count < 2 || a[0].Type != DataType.Table) return DynValue.Nil;
return WorldObjectIndex(s, ctx, a[0].Table, a[1].CastToString() ?? string.Empty);
});
mt["__tostring"] = DynValue.NewCallback((c, a) =>
{
uint id = a.Count > 0 ? LuaArgs.Id(a[0]) : 0;
string name = Host.TryGetObjectName(id, out string n) ? n : "?";
return DynValue.NewString($"{name} [0x{id:X8}]");
});
mt["__eq"] = DynValue.NewCallback((c, a) =>
{
uint x = a.Count > 0 ? LuaArgs.Id(a[0]) : 0;
uint y = a.Count > 1 ? LuaArgs.Id(a[1]) : 0;
return DynValue.NewBoolean(x != 0 && x == y);
});
_worldObjectMeta[s] = mt;
ctx.OnStop.Add(() => _worldObjectMeta.Remove(s));
return mt;
}
private DynValue WorldObjectIndex(Script s, ScriptContext ctx, Table obj, string key)
{
DynValue idv = obj.Get("Id");
if (idv.Type != DataType.Number) return DynValue.Nil;
uint id = (uint)idv.Number;
switch (key)
{
case "Name":
return DynValue.NewString(Host.TryGetObjectName(id, out string name) ? name : string.Empty);
case "WeenieClassId":
return DynValue.NewNumber(Host.TryGetObjectWcid(id, out uint wcid) ? wcid : 0);
case "ObjectClass":
return DynValue.NewNumber(WorldClassOf(id));
case "ObjectClassName":
{
int oc = WorldClassOf(id);
return DynValue.NewString(oc >= 0 && oc < LuaEnums.ObjectClass.Length ? LuaEnums.ObjectClass[oc] : "Unknown");
}
case "ObjectType": // a typed ObjectType value (UB: wo.ObjectType == ObjectType.Creature)
return LuaEnumValues.Get(s, "ObjectType", Host.TryGetItemType(id, out uint type) ? type : 0);
// Enum-valued int properties, as numbers (compare with the enum globals).
case "ValidWieldedLocations": return IntProp(id, 9);
case "ClothingPriority": return IntProp(id, 4);
case "Material": return IntProp(id, 131);
case "AmmoType": return IntProp(id, 50);
case "TargetType": return IntProp(id, 94);
case "CombatUse": return IntProp(id, 51);
case "RadarColor": return IntProp(id, 95);
case "RadarBehavior": return IntProp(id, 133);
case "IconEffects": return IntProp(id, 18);
case "ObjectDescriptionFlag": // PublicWeenieDesc bitfield (compare with ObjectDescriptionFlag.X)
return DynValue.NewNumber(Host.HasGetObjectBitfield && Host.TryGetObjectBitfield(id, out uint bits) ? bits : 0);
case "PhysicsState": // the last SetState the server sent (PhysicsState flags), 0 when none seen
return DynValue.NewNumber(Host.HasGetObjectState && Host.TryGetObjectState(id, out uint ps) ? ps : 0);
case "CombatMode":
return id == Host.GetPlayerId() ? DynValue.NewNumber(Host.GetCurrentCombatMode()) : IntProp(id, 40);
case "SpellId":
if (Host.TryGetObjectDataIdProperty(id, 28, out uint spell) && spell != 0) return DynValue.NewNumber(spell);
return DynValue.NewNumber(WorldSpellIds(id) is { Count: > 0 } sp ? sp[0] : 0);
case "SpellIds":
return LayeredList(s, WorldSpellIds(id));
case "EnchantmentIds":
return LayeredList(s, WorldEnchantmentIds(id));
// Lists (UB: properties; Items is also still callable, wo:Items()).
case "ItemIds": return IdList(s, WorldChildIds(id, containers: false));
case "Items": return ObjectList(s, ctx, WorldChildIds(id, containers: false));
case "ContainerIds": return IdList(s, WorldChildIds(id, containers: true));
case "Containers": return ObjectList(s, ctx, WorldChildIds(id, containers: true));
case "AllItemIds": return IdList(s, WorldAllItemIds(id));
case "AllItems": return ObjectList(s, ctx, WorldAllItemIds(id));
case "EquipmentIds": return IdList(s, WorldWieldedIds(id));
case "Equipment": return ObjectList(s, ctx, WorldWieldedIds(id));
case "ServerPosition":
return WorldServerPosition(s, id);
case "Vitals":
case "Skills":
case "Attributes":
{
// The player's own stats (UB keeps them on game.Character.Weenie); other
// objects' stats aren't readable, so theirs are empty.
if (id == Host.GetPlayerId())
{
DynValue t = s.Registry.Get("rynth.character." + key);
if (t.Type == DataType.Table) return t;
}
return DynValue.NewTable(new Table(s));
}
case "OnPositionChanged":
// Baseline now, so a move right after subscribing is seen.
if (!_worldWatchedPos.ContainsKey(id) && WorldTryGetPosition(id, out WorldPos now)) _worldWatchedPos[id] = now;
return ctx.Event($"WorldObject.{key}:{id}").CreateTable(s);
case "OnDestroyed":
return ctx.Event($"WorldObject.{key}:{id}").CreateTable(s);
case "ContainerId":
return DynValue.NewNumber(Host.TryGetObjectOwnershipInfo(id, out uint container, out _, out _) ? container : 0);
case "WielderId":
return DynValue.NewNumber(Host.TryGetObjectOwnershipInfo(id, out _, out uint wielder, out _) ? wielder : 0);
case "Container":
return Host.TryGetObjectOwnershipInfo(id, out uint cid, out _, out _) ? WrapObject(s, ctx, cid) : DynValue.Nil;
case "Wielder":
return Host.TryGetObjectOwnershipInfo(id, out _, out uint wid, out _) ? WrapObject(s, ctx, wid) : DynValue.Nil;
case "CurrentWieldedLocation":
if (Host.TryGetObjectOwnershipInfo(id, out _, out _, out uint loc)) return DynValue.NewNumber(loc);
return DynValue.NewNumber(Host.TryGetObjectIntProperty(id, IntCurrentWieldedLocation, out int l) ? l : 0);
case "Burden":
return DynValue.NewNumber(Host.TryGetObjectIntProperty(id, IntBurden, out int burden) ? burden : 0);
case "StackSize":
return DynValue.NewNumber(Host.TryGetObjectIntProperty(id, IntStackSize, out int stack) && stack > 0 ? stack : 1);
case "HasAppraisalData":
return DynValue.NewBoolean(Host.HasAppraisalData(id));
case "Position":
return WorldPositionTable(s, id);
// Methods: bound to this object on first use and kept as a raw field.
case "IntValue":
case "FloatValue":
case "StringValue":
case "BoolValue":
case "DataValue":
case "Int64Value":
case "DistanceTo":
case "DistanceTo2D":
case "DistanceTo2d":
case "DistanceTo3D":
case "Value":
case "HasValue":
case "GetTopmostParent":
{
DynValue fn = WorldObjectMethod(s, ctx, obj, id, key);
obj.Set(key, fn);
return fn;
}
default:
return DynValue.Nil;
}
}
private DynValue WorldObjectMethod(Script s, ScriptContext ctx, Table obj, uint id, string key)
{
switch (key)
{
case "IntValue":
return DynValue.NewCallback((c, a) =>
{
var args = LuaArgs.Of(a, obj);
uint stype = PropertyIdArg(args, "IntValue");
return Host.TryGetObjectIntProperty(id, stype, out int v) ? DynValue.NewNumber(v) : DefaultArg(args, DynValue.NewNumber(0));
});
case "Int64Value":
return DynValue.NewCallback((c, a) =>
{
var args = LuaArgs.Of(a, obj);
uint stype = PropertyIdArg(args, "Int64Value");
return Host.TryGetObjectQuadProperty(id, stype, out long v) ? DynValue.NewNumber(v) : DefaultArg(args, DynValue.NewNumber(0));
});
case "FloatValue":
return DynValue.NewCallback((c, a) =>
{
var args = LuaArgs.Of(a, obj);
uint stype = PropertyIdArg(args, "FloatValue");
return Host.TryGetObjectDoubleProperty(id, stype, out double v) ? DynValue.NewNumber(v) : DefaultArg(args, DynValue.NewNumber(0));
});
case "StringValue":
return DynValue.NewCallback((c, a) =>
{
var args = LuaArgs.Of(a, obj);
uint stype = PropertyIdArg(args, "StringValue");
return Host.TryGetObjectStringProperty(id, stype, out string v) ? DynValue.NewString(v) : DefaultArg(args, DynValue.NewString(string.Empty));
});
case "BoolValue":
return DynValue.NewCallback((c, a) =>
{
var args = LuaArgs.Of(a, obj);
uint stype = PropertyIdArg(args, "BoolValue");
return Host.TryGetObjectBoolProperty(id, stype, out bool v) ? DynValue.NewBoolean(v) : DefaultArg(args, DynValue.False);
});
case "DataValue":
return DynValue.NewCallback((c, a) =>
{
var args = LuaArgs.Of(a, obj);
uint stype = PropertyIdArg(args, "DataValue");
return Host.TryGetObjectDataIdProperty(id, stype, out uint v) ? DynValue.NewNumber(v) : DefaultArg(args, DynValue.NewNumber(0));
});
case "DistanceTo":
case "DistanceTo3D":
case "DistanceTo2D":
case "DistanceTo2d": // UB's id overload
{
bool flat = key is "DistanceTo2D" or "DistanceTo2d";
return DynValue.NewCallback((c, a) =>
{
DynValue other = LuaArgs.At(LuaArgs.Of(a, obj), 0);
uint otherId = LuaArgs.Id(other);
if (otherId == 0)
throw new ScriptRuntimeException($"{key}(other) needs a WorldObject or an object id");
if (!WorldTryGetPosition(id, out WorldPos p1) || !WorldTryGetPosition(otherId, out WorldPos p2))
return DynValue.NewNumber(double.PositiveInfinity); // unknown position: never "in range"
double d = flat ? p1.DistanceTo2D(p2) : p1.DistanceTo(p2);
return DynValue.NewNumber(double.IsFinite(d) ? d : double.PositiveInfinity);
});
}
case "Value":
// UB: wo:Value(IntId.X [, default]); the key's enum picks the property kind (a
// plain number is an IntId). wo:Value() with no key is the object's value in pyreals.
return DynValue.NewCallback((c, a) =>
{
var args = LuaArgs.Of(a, obj);
if (args.Length == 0 || args[0].IsNil())
return DynValue.NewNumber(Host.TryGetObjectIntProperty(id, IntValueProp, out int pv) ? pv : 0);
return WorldReadValue(id, args[0], out DynValue v, "Value") ? v : DefaultArg(args, WorldValueDefault(args[0]));
});
case "HasValue":
return DynValue.NewCallback((c, a) =>
DynValue.NewBoolean(WorldReadValue(id, LuaArgs.At(LuaArgs.Of(a, obj), 0), out _, "HasValue")));
case "GetTopmostParent":
return DynValue.NewCallback((c, a) => WrapObject(s, ctx, WorldTopmostParent(id)));
default:
return DynValue.Nil;
}
}
private static uint PropertyIdArg(DynValue[] args, string what)
{
DynValue v = LuaArgs.At(args, 0);
double d = LuaArgs.Num(v, -1);
if (d < 0 || v.IsNil())
throw new ScriptRuntimeException($"{what}(propertyId [, default]) needs a property id number, e.g. wo:{what}(5)");
return (uint)d;
}
/// <summary>The caller's default (even an explicit nil) when given, else UtilityBelt's (0, "", false).</summary>
private static DynValue DefaultArg(DynValue[] args, DynValue fallback) => args.Length > 1 ? args[1] : fallback;
// ── UtilityBelt's WorldObject extras ────────────────────────────────────
private DynValue IntProp(uint id, uint stype) =>
DynValue.NewNumber(Host.TryGetObjectIntProperty(id, stype, out int v) ? v : 0);
/// <summary>
/// wo:Value(key) / wo:HasValue(key): the property kind comes from the key's enum (typed
/// Int64Id, FloatId, StringId, BoolId, DataId, InstanceId); a plain number is an IntId.
/// </summary>
private bool WorldReadValue(uint id, DynValue key, out DynValue value, string what)
{
value = DynValue.Nil;
if (LuaEnumValues.TryRead(key, out string kind, out long n))
{
uint stype = (uint)n;
switch (kind)
{
case "StringId":
if (!Host.TryGetObjectStringProperty(id, stype, out string sv)) return false;
value = DynValue.NewString(sv);
return true;
case "FloatId":
if (!Host.TryGetObjectDoubleProperty(id, stype, out double dv)) return false;
value = DynValue.NewNumber(dv);
return true;
case "BoolId":
if (!Host.TryGetObjectBoolProperty(id, stype, out bool bv)) return false;
value = DynValue.NewBoolean(bv);
return true;
case "DataId":
if (!Host.TryGetObjectDataIdProperty(id, stype, out uint did)) return false;
value = DynValue.NewNumber(did);
return true;
case "Int64Id":
if (!Host.TryGetObjectQuadProperty(id, stype, out long qv)) return false;
value = DynValue.NewNumber(qv);
return true;
case "InstanceId":
{
// API v73 engines answer every PropertyInstanceId (Monarch, Allegiance,
// Patron, PetOwner, HouseOwner, ...); older ones serve ownership only:
// Container (2) and Wielder (3).
uint iv;
if (Host.HasGetObjectInstanceIdProperty)
{
if (!Host.TryGetObjectInstanceIdProperty(id, stype, out iv)) return false;
}
else
{
if (stype is not (2 or 3) || !Host.TryGetObjectOwnershipInfo(id, out uint container, out uint wielder, out _)) return false;
iv = stype == 2 ? container : wielder;
}
if (iv == 0) return false;
value = DynValue.NewNumber(iv);
return true;
}
default:
throw new ScriptRuntimeException($"{what}(key): {kind} isn't a property id (use IntId, Int64Id, FloatId, StringId, BoolId, DataId or InstanceId)");
}
}
if (key.Type == DataType.Number)
{
if (!Host.TryGetObjectIntProperty(id, (uint)key.Number, out int iv)) return false;
value = DynValue.NewNumber(iv);
return true;
}
throw new ScriptRuntimeException($"{what}(key [, default]) needs a property id, e.g. wo:{what}(IntId.Value) or wo:{what}(StringId.Name)");
}
/// <summary>UtilityBelt's default for a missing property: "" for strings, false for bools, else 0.</summary>
private static DynValue WorldValueDefault(DynValue key)
{
if (LuaEnumValues.TryRead(key, out string kind, out _))
return kind switch { "StringId" => DynValue.NewString(string.Empty), "BoolId" => DynValue.False, _ => DynValue.NewNumber(0) };
return DynValue.NewNumber(0);
}
/// <summary>What <paramref name="id"/> directly holds: items (<paramref name="containers"/> false) or side packs.</summary>
private List<uint> WorldChildIds(uint id, bool containers)
{
var list = new List<uint>();
if (id == 0 || !Host.HasGetContainerContents) return list;
uint[] buf = new uint[512];
int n = Host.GetContainerContents(id, buf);
for (int i = 0; i < n; i++)
{
bool isPack = Host.TryGetItemType(buf[i], out uint t) && (t & ItemTypeContainer) != 0;
if (isPack == containers) list.Add(buf[i]);
}
return list;
}
/// <summary>Every item <paramref name="id"/> holds, side packs' contents included (not the packs).</summary>
private List<uint> WorldAllItemIds(uint id)
{
var list = WorldChildIds(id, containers: false);
foreach (uint pack in WorldChildIds(id, containers: true))
list.AddRange(WorldChildIds(pack, containers: false));
return list;
}
private List<uint> WorldSpellIds(uint id)
{
var list = new List<uint>();
if (!Host.HasGetObjectSpellIds) return list;
uint[] buf = new uint[64];
int n = Host.GetObjectSpellIds(id, buf, buf.Length);
for (int i = 0; i < Math.Min(n, buf.Length); i++) if (buf[i] != 0) list.Add(buf[i]);
return list;
}
private List<uint> WorldEnchantmentIds(uint id)
{
var list = new List<uint>();
if (!Host.HasReadObjectEnchantments) return list;
uint[] ids = new uint[256];
double[] exp = new double[256];
int n = Host.ReadObjectEnchantments(id, ids, exp, ids.Length);
for (int i = 0; i < Math.Min(n, ids.Length); i++) if (ids[i] != 0) list.Add(ids[i]);
return list;
}
/// <summary>UB's LayeredSpellId list: <c>{ Id = spellId }</c> per spell (the layer isn't known here).</summary>
private static DynValue LayeredList(Script s, List<uint> spells)
{
var t = new Table(s);
for (int i = 0; i < spells.Count; i++)
{
var e = new Table(s);
e["Id"] = (double)spells[i];
t.Set(i + 1, DynValue.NewTable(e));
}
return LuaLists.Wrap(s, t);
}
internal static DynValue IdList(Script s, List<uint> ids)
{
var t = new Table(s);
for (int i = 0; i < ids.Count; i++) t.Set(i + 1, DynValue.NewNumber(ids[i]));
return LuaLists.Wrap(s, t);
}
internal DynValue ObjectList(Script s, ScriptContext ctx, List<uint> ids)
{
var t = new Table(s);
int n = 0;
foreach (uint id in ids) t.Set(++n, WrapObject(s, ctx, id));
return LuaLists.Wrap(s, t);
}
/// <summary>The outermost container or wielder holding <paramref name="id"/> (itself when nothing holds it).</summary>
private uint WorldTopmostParent(uint id)
{
uint cur = id;
for (int depth = 0; depth < 8; depth++)
{
if (!Host.TryGetObjectOwnershipInfo(cur, out uint container, out uint wielder, out _)) break;
uint parent = container != 0 ? container : wielder;
if (parent == 0 || parent == cur) break;
cur = parent;
}
return cur;
}
/// <summary>
/// UB's ServerPosition: <c>{ Landcell, Frame = { Origin = {X, Y, Z}, Orientation = {W, X, Y, Z} } }</c>
/// with <c>DistanceTo2D(pos)</c> / <c>DistanceTo3D(pos)</c>; nil when the object has no
/// position (in a pack, wielded, or not in view).
/// </summary>
internal DynValue WorldServerPosition(Script s, uint id)
{
if (!WorldTryGetPosition(id, out WorldPos p)) return DynValue.Nil;
float qw = 1, qx = 0, qy = 0, qz = 0;
if (id == Host.GetPlayerId() && Host.HasGetPlayerPose)
Host.TryGetPlayerPose(out _, out _, out _, out _, out qw, out qx, out qy, out qz);
else if (Host.HasGetObjectHeading && Host.TryGetObjectHeading(id, out float heading))
{
double half = -heading * Math.PI / 360.0;
qw = (float)Math.Cos(half);
qz = (float)Math.Sin(half);
}
var origin = new Table(s);
origin["X"] = (double)p.X; origin["Y"] = (double)p.Y; origin["Z"] = (double)p.Z;
var orient = new Table(s);
orient["W"] = (double)qw; orient["X"] = (double)qx; orient["Y"] = (double)qy; orient["Z"] = (double)qz;
var frame = new Table(s);
frame["Origin"] = DynValue.NewTable(origin);
frame["Orientation"] = DynValue.NewTable(orient);
var t = new Table(s);
t["Landcell"] = (double)p.Cell;
t["Frame"] = DynValue.NewTable(frame);
t.MetaTable = PositionMeta(s);
return DynValue.NewTable(t);
}
private static Table PositionMeta(Script s)
{
DynValue cached = s.Registry.Get("rynth.positionmeta");
if (cached.Type == DataType.Table) return cached.Table;
var methods = new Table(s);
DynValue Dist(bool flat) => DynValue.NewCallback((c, a) =>
{
if (a.Count < 2 || !TryPosition(a[0], out WorldPos p1) || !TryPosition(a[1], out WorldPos p2))
throw new ScriptRuntimeException($"{(flat ? "DistanceTo2D" : "DistanceTo3D")}(position) needs a Position (wo.ServerPosition)");
return DynValue.NewNumber(flat ? p1.DistanceTo2D(p2) : p1.DistanceTo(p2));
});
methods["DistanceTo2D"] = Dist(true);
methods["DistanceTo3D"] = Dist(false);
var mt = new Table(s);
mt["__index"] = DynValue.NewTable(methods);
mt["__tostring"] = DynValue.NewCallback((c, a) =>
DynValue.NewString(TryPosition(a[0], out WorldPos p) ? $"Position 0x{p.Cell:X8} [{p.X:0.00} {p.Y:0.00} {p.Z:0.00}]" : "Position"));
s.Registry.Set("rynth.positionmeta", DynValue.NewTable(mt));
return mt;
}
private static bool TryPosition(DynValue v, out WorldPos pos)
{
pos = default;
if (v.Type != DataType.Table) return false;
DynValue cell = v.Table.Get("Landcell");
DynValue frame = v.Table.Get("Frame");
if (cell.Type != DataType.Number || frame.Type != DataType.Table) return false;
DynValue origin = frame.Table.Get("Origin");
if (origin.Type != DataType.Table) return false;
pos = new WorldPos((uint)cell.Number, (float)LuaArgs.Num(origin.Table.Get("X")),
(float)LuaArgs.Num(origin.Table.Get("Y")), (float)LuaArgs.Num(origin.Table.Get("Z")));
return true;
}
// ── Per-object events (OnPositionChanged, OnDestroyed) ──────────────────
private readonly Dictionary<uint, WorldPos> _worldWatchedPos = new();
/// <summary>Polls the positions of objects some script watches with wo.OnPositionChanged.</summary>
private void WorldPollPositions()
{
const string prefix = "WorldObject.OnPositionChanged:";
HashSet<uint>? watched = null;
foreach (var ctx in _scripts.Values)
{
if (!ctx.Host.Loaded) continue;
foreach (string key in ctx.EventKeys(prefix))
if (uint.TryParse(key.AsSpan(prefix.Length), out uint id)) (watched ??= new()).Add(id);
}
if (watched == null) { _worldWatchedPos.Clear(); return; }
foreach (uint id in new List<uint>(_worldWatchedPos.Keys))
if (!watched.Contains(id)) _worldWatchedPos.Remove(id);
foreach (uint id in watched)
{
if (!WorldTryGetPosition(id, out WorldPos p)) continue;
bool had = _worldWatchedPos.TryGetValue(id, out WorldPos old);
_worldWatchedPos[id] = p;
if (!had || (old.Cell == p.Cell && old.X == p.X && old.Y == p.Y && old.Z == p.Z)) continue;
uint oid = id;
FireWorld(prefix + oid, (s, ctx) =>
{
var t = new Table(s);
t["Weenie"] = WrapObject(s, ctx, oid);
t["Position"] = WorldServerPosition(s, oid);
return DynValue.NewTable(t);
});
}
}
/// <summary>wo.OnDestroyed for a released object (then its per-object events are dropped).</summary>
private void WorldFireDestroyed(uint id)
{
string key = "WorldObject.OnDestroyed:" + id;
FireAll(key, s =>
{
var t = new Table(s);
t["ObjectId"] = (double)id;
return DynValue.NewTable(t);
});
foreach (var ctx in _scripts.Values)
{
ctx.DropEvent(key);
ctx.DropEvent("WorldObject.OnPositionChanged:" + id);
}
_worldWatchedPos.Remove(id);
}
// ── Position ────────────────────────────────────────────────────────────
internal readonly struct WorldPos
{
public readonly uint Cell;
public readonly float X, Y, Z;
public WorldPos(uint cell, float x, float y, float z)
{
Cell = cell;
X = x;
Y = y;
Z = z;
}
// Landblock-local → global: each landblock is 192 m across (same as RynthAi's distance).
private double GX => ((Cell >> 24) & 0xFF) * 192.0 + X;
private double GY => ((Cell >> 16) & 0xFF) * 192.0 + Y;
public double DistanceTo2D(in WorldPos o)
{
double dx = GX - o.GX, dy = GY - o.GY;
return Math.Sqrt(dx * dx + dy * dy);
}
public double DistanceTo(in WorldPos o)
{
double dx = GX - o.GX, dy = GY - o.GY, dz = (double)Z - o.Z;
return Math.Sqrt(dx * dx + dy * dy + dz * dz);
}
}
/// <summary>An object's position; the player's from its pose (fresher than the object snapshot).</summary>
internal bool WorldTryGetPosition(uint id, out WorldPos pos)
{
pos = default;
if (id == 0) return false;
if (id == Host.GetPlayerId() && Host.HasGetPlayerPose
&& Host.TryGetPlayerPose(out uint pc, out float px, out float py, out float pz, out _, out _, out _, out _) && pc != 0)
{
pos = new WorldPos(pc, px, py, pz);
return true;
}
if (!Host.TryGetObjectPosition(id, out uint cell, out float x, out float y, out float z) || cell == 0) return false;
if (!float.IsFinite(x) || !float.IsFinite(y) || !float.IsFinite(z)) return false;
pos = new WorldPos(cell, x, y, z);
return true;
}
private DynValue WorldPositionTable(Script s, uint id)
{
if (!WorldTryGetPosition(id, out WorldPos p)) return DynValue.Nil;
var t = new Table(s);
t["Landcell"] = (double)p.Cell;
t["X"] = (double)p.X;
t["Y"] = (double)p.Y;
t["Z"] = (double)p.Z;
if (NavCoordinateHelper.TryConvertPoseToCoords(p.Cell, p.X, p.Y, out double ns, out double ew))
{
t["NS"] = ns;
t["EW"] = ew;
}
return DynValue.NewTable(t);
}
// ── ObjectClass ─────────────────────────────────────────────────────────
/// <summary>The object's ObjectClass (LuaEnums numbering); cached once it came from reliable data.</summary>
internal int WorldClassOf(uint id)
{
if (_worldClass.TryGetValue(id, out int cls)) return cls;
cls = WorldClassify(id, out bool certain);
if (certain) _worldClass[id] = cls;
return cls;
}
private static readonly int OcUnknown = LuaEnums.ObjectClassOf("Unknown");
private static readonly int OcMeleeWeapon = LuaEnums.ObjectClassOf("MeleeWeapon");
private static readonly int OcArmor = LuaEnums.ObjectClassOf("Armor");
private static readonly int OcClothing = LuaEnums.ObjectClassOf("Clothing");
private static readonly int OcJewelry = LuaEnums.ObjectClassOf("Jewelry");
private static readonly int OcMonster = LuaEnums.ObjectClassOf("Monster");
private static readonly int OcFood = LuaEnums.ObjectClassOf("Food");
private static readonly int OcMoney = LuaEnums.ObjectClassOf("Money");
private static readonly int OcMisc = LuaEnums.ObjectClassOf("Misc");
private static readonly int OcMissileWeapon = LuaEnums.ObjectClassOf("MissileWeapon");
private static readonly int OcContainer = LuaEnums.ObjectClassOf("Container");
private static readonly int OcGem = LuaEnums.ObjectClassOf("Gem");
private static readonly int OcSpellComponent = LuaEnums.ObjectClassOf("SpellComponent");
private static readonly int OcKey = LuaEnums.ObjectClassOf("Key");
private static readonly int OcPortal = LuaEnums.ObjectClassOf("Portal");
private static readonly int OcTradeNote = LuaEnums.ObjectClassOf("TradeNote");
private static readonly int OcManaStone = LuaEnums.ObjectClassOf("ManaStone");
private static readonly int OcBaseCooking = LuaEnums.ObjectClassOf("BaseCooking");
private static readonly int OcBaseAlchemy = LuaEnums.ObjectClassOf("BaseAlchemy");
private static readonly int OcBaseFletching = LuaEnums.ObjectClassOf("BaseFletching");
private static readonly int OcCraftedAlchemy = LuaEnums.ObjectClassOf("CraftedAlchemy");
private static readonly int OcCraftedFletching = LuaEnums.ObjectClassOf("CraftedFletching");
private static readonly int OcPlayer = LuaEnums.ObjectClassOf("Player");
private static readonly int OcVendor = LuaEnums.ObjectClassOf("Vendor");
private static readonly int OcDoor = LuaEnums.ObjectClassOf("Door");
private static readonly int OcCorpse = LuaEnums.ObjectClassOf("Corpse");
private static readonly int OcLifestone = LuaEnums.ObjectClassOf("Lifestone");
private static readonly int OcHealingKit = LuaEnums.ObjectClassOf("HealingKit");
private static readonly int OcLockpick = LuaEnums.ObjectClassOf("Lockpick");
private static readonly int OcWandStaffOrb = LuaEnums.ObjectClassOf("WandStaffOrb");
private static readonly int OcBook = LuaEnums.ObjectClassOf("Book");
private static readonly int OcNpc = LuaEnums.ObjectClassOf("Npc");
private static readonly int OcFoci = LuaEnums.ObjectClassOf("Foci");
private static readonly int OcSalvage = LuaEnums.ObjectClassOf("Salvage");
private static readonly int OcUst = LuaEnums.ObjectClassOf("Ust");
private static readonly int OcServices = LuaEnums.ObjectClassOf("Services");
private static readonly int OcScroll = LuaEnums.ObjectClassOf("Scroll");
/// <summary>
/// Decal/UtilityBelt-style ObjectClass from the PublicWeenieDesc bitfield (player, vendor,
/// corpse, door, portal, lifestone, attackable) and the ItemType flags, names only as a
/// fallback. <paramref name="certain"/> is false when the data it needs wasn't readable yet
/// (a fresh object), so the caller retries later instead of caching a guess.
/// </summary>
private int WorldClassify(uint id, out bool certain)
{
certain = false;
uint pid = Host.GetPlayerId();
if (id == pid && pid != 0) { certain = true; return OcPlayer; }
uint bf = 0;
bool gotBf = Host.HasGetObjectBitfield && Host.TryGetObjectBitfield(id, out bf) && bf != 0;
if (!gotBf) bf = 0;
bool gotType = Host.TryGetItemType(id, out uint type) && type != 0;
Host.TryGetObjectName(id, out string name);
if (gotBf)
{
if ((bf & BfPlayer) != 0) { certain = true; return OcPlayer; }
if ((bf & BfVendor) != 0) { certain = true; return OcVendor; }
if ((bf & BfCorpse) != 0) { certain = true; return OcCorpse; }
if ((bf & BfDoor) != 0) { certain = true; return OcDoor; }
if ((bf & BfPortal) != 0) { certain = true; return OcPortal; }
if ((bf & BfLifestone) != 0) { certain = true; return OcLifestone; }
}
if (gotType && (type & ItemTypeCreature) != 0)
{
if (gotBf) { certain = true; return (bf & BfAttackable) != 0 ? OcMonster : OcNpc; }
// No bitfield yet: the engine's attackable snapshot is the next best signal.
return Host.HasObjectIsAttackable && Host.ObjectIsAttackable(id) ? OcMonster : OcNpc;
}
if (!gotBf && IsCorpseName(name)) return OcCorpse;
if (gotBf)
{
if ((bf & BfHealer) != 0) { certain = true; return OcHealingKit; }
if ((bf & BfLockpick) != 0) { certain = true; return OcLockpick; }
}
if (gotType)
{
certain = true;
int cls = ClassifyByItemType(type);
if (cls == OcBook && name.Contains("Scroll", StringComparison.OrdinalIgnoreCase)) return OcScroll;
if (name.StartsWith("Foci of", StringComparison.OrdinalIgnoreCase)) return OcFoci;
if (cls == OcMisc && gotBf && (bf & BfFood) != 0) return OcFood;
return cls;
}
if (gotBf && (bf & BfFood) != 0) { certain = true; return OcFood; }
return OcUnknown;
}
private static int ClassifyByItemType(uint t)
{
// Most specific first (the order RynthAi's cache uses).
if ((t & ItemTypePromissoryNote) != 0) return OcTradeNote;
if ((t & ItemTypeManaStone) != 0) return OcManaStone;
if ((t & ItemTypeSpellComponents) != 0) return OcSpellComponent;
if ((t & ItemTypeGem) != 0) return OcGem;
if ((t & ItemTypeKey) != 0) return OcKey;
if ((t & ItemTypeLifeStone) != 0) return OcLifestone;
if ((t & ItemTypeTinkeringMaterial) != 0) return OcSalvage;
if ((t & ItemTypeTinkeringTool) != 0) return OcUst;
if ((t & ItemTypeCraftCookingBase) != 0) return OcBaseCooking;
if ((t & ItemTypeCraftAlchemyBase) != 0) return OcBaseAlchemy;
if ((t & ItemTypeCraftFletchingBase) != 0) return OcBaseFletching;
if ((t & ItemTypeCraftAlchemyIntermediate) != 0) return OcCraftedAlchemy;
if ((t & ItemTypeCraftFletchingIntermediate) != 0) return OcCraftedFletching;
if ((t & ItemTypeService) != 0) return OcServices;
if ((t & ItemTypePortal) != 0) return OcPortal;
if ((t & ItemTypeWritable) != 0) return OcBook;
if ((t & ItemTypeContainer) != 0) return OcContainer;
if ((t & ItemTypeCaster) != 0) return OcWandStaffOrb;
if ((t & ItemTypeMissileWeapon) != 0) return OcMissileWeapon;
if ((t & ItemTypeArmor) != 0) return OcArmor;
if ((t & ItemTypeMeleeWeapon) != 0) return OcMeleeWeapon;
if ((t & ItemTypeClothing) != 0) return OcClothing;
if ((t & ItemTypeJewelry) != 0) return OcJewelry;
if ((t & ItemTypeFood) != 0) return OcFood;
if ((t & ItemTypeMoney) != 0) return OcMoney;
if ((t & ItemTypeMisc) != 0) return OcMisc;
return OcUnknown;
}
private static bool IsCorpseName(string name) =>
!string.IsNullOrWhiteSpace(name)
&& (name.EndsWith(" corpse", StringComparison.OrdinalIgnoreCase)
|| name.Contains("'s corpse", StringComparison.OrdinalIgnoreCase)
|| name.StartsWith("corpse of ", StringComparison.OrdinalIgnoreCase));
}

View file

@ -0,0 +1,174 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.Json;
namespace RynthCore.Plugin.RynthLua;
/// <summary>
/// The player's last show/hide choice for each script window, per character (design doc §8
/// decision 9): <c>hud_visibility.json</c> in RynthLua's data folder,
/// <c>{"server|character": {"RynthLua/script/hud": true|false, ...}, ...}</c>.
///
/// Only the player's choices are recorded (the window's X, the bar's Scripts menu,
/// <c>/rc ui</c>, <c>/lua hud show|hide|toggle</c>); a script's own <c>hud.Visible = ...</c> is not.
/// Characters never share entries. Read lazily with JsonDocument and written with
/// Utf8JsonWriter (no serialized types, so nothing pins the plugin's load context), about 2 s
/// after the last change, and on logout and shutdown. Every file operation is caught; a bad or
/// missing file is treated as empty. Pump thread only.
/// </summary>
internal sealed class HudVisibilityMemory
{
public const int MaxKeysPerCharacter = 500;
private const long SaveDelayMs = 2000;
private readonly string _path;
private readonly Action<string> _log;
// character → window key → (visible, stamp). The stamp orders entries oldest first, so the
// cap drops the choice made longest ago.
private Dictionary<string, Dictionary<string, (bool Visible, long Stamp)>>? _data;
private long _stamp;
private bool _dirty;
private long _dirtyAtMs;
private readonly HashSet<string> _failuresLogged = new(StringComparer.Ordinal);
public HudVisibilityMemory(string path, Action<string> log)
{
_path = path;
_log = log;
}
public string Path => _path;
public bool Dirty => _dirty;
/// <summary>The player's remembered choice for <paramref name="windowKey"/> on <paramref name="character"/>.</summary>
public bool TryGet(string character, string windowKey, out bool visible)
{
visible = false;
if (string.IsNullOrEmpty(character) || string.IsNullOrEmpty(windowKey)) return false;
Load();
if (_data!.TryGetValue(character, out var windows) && windows.TryGetValue(windowKey, out var e))
{
visible = e.Visible;
return true;
}
return false;
}
/// <summary>Records the player's choice. No-op before login (empty character).</summary>
public void Record(string character, string windowKey, bool visible, long nowMs)
{
if (string.IsNullOrEmpty(character) || string.IsNullOrEmpty(windowKey)) return;
Load();
if (!_data!.TryGetValue(character, out var windows))
_data[character] = windows = new Dictionary<string, (bool, long)>(StringComparer.Ordinal);
if (windows.TryGetValue(windowKey, out var old) && old.Visible == visible)
{
windows[windowKey] = (visible, ++_stamp); // same choice: just freshen it for the cap
return;
}
windows[windowKey] = (visible, ++_stamp);
Trim(windows);
_dirty = true;
_dirtyAtMs = nowMs;
}
/// <summary>Called every tick: writes the file once changes have been quiet for about 2 s.</summary>
public void Tick(long nowMs)
{
if (_dirty && nowMs - _dirtyAtMs >= SaveDelayMs) Save();
}
/// <summary>Writes pending changes now (logout, shutdown).</summary>
public void Flush()
{
if (_dirty) Save();
}
private static void Trim(Dictionary<string, (bool Visible, long Stamp)> windows)
{
if (windows.Count <= MaxKeysPerCharacter) return;
foreach (string key in windows.OrderBy(kv => kv.Value.Stamp).Take(windows.Count - MaxKeysPerCharacter).Select(kv => kv.Key).ToList())
windows.Remove(key);
}
private void Load()
{
if (_data != null) return;
_data = new Dictionary<string, Dictionary<string, (bool, long)>>(StringComparer.Ordinal);
try
{
if (!File.Exists(_path)) return;
byte[] bytes = File.ReadAllBytes(_path);
if (bytes.Length == 0) return;
using JsonDocument doc = JsonDocument.Parse(bytes, new JsonDocumentOptions
{
AllowTrailingCommas = true,
CommentHandling = JsonCommentHandling.Skip,
MaxDepth = 8,
});
if (doc.RootElement.ValueKind != JsonValueKind.Object) return;
foreach (JsonProperty ch in doc.RootElement.EnumerateObject())
{
if (ch.Name.Length == 0 || ch.Value.ValueKind != JsonValueKind.Object) continue;
var windows = new Dictionary<string, (bool, long)>(StringComparer.Ordinal);
foreach (JsonProperty w in ch.Value.EnumerateObject())
{
if (w.Name.Length == 0) continue;
if (w.Value.ValueKind == JsonValueKind.True) windows[w.Name] = (true, ++_stamp);
else if (w.Value.ValueKind == JsonValueKind.False) windows[w.Name] = (false, ++_stamp);
}
Trim(windows);
if (windows.Count > 0) _data[ch.Name] = windows;
}
}
catch (Exception ex)
{
// A bad file counts as empty; the next save replaces it.
_data.Clear();
Fail("read", $"can't read {_path}: {ex.Message}; starting with no remembered hud visibility");
}
}
private void Save()
{
_dirty = false;
if (_data == null) return;
string tmp = _path + ".tmp";
try
{
using (var buffer = new MemoryStream())
{
using (var w = new Utf8JsonWriter(buffer, new JsonWriterOptions { Indented = true }))
{
w.WriteStartObject();
foreach (var ch in _data.OrderBy(kv => kv.Key, StringComparer.Ordinal))
{
if (ch.Value.Count == 0) continue;
w.WriteStartObject(ch.Key);
foreach (var e in ch.Value.OrderBy(kv => kv.Value.Stamp))
w.WriteBoolean(e.Key, e.Value.Visible);
w.WriteEndObject();
}
w.WriteEndObject();
}
string? dir = System.IO.Path.GetDirectoryName(_path);
if (!string.IsNullOrEmpty(dir)) Directory.CreateDirectory(dir);
File.WriteAllBytes(tmp, buffer.ToArray());
}
File.Move(tmp, _path, overwrite: true);
}
catch (Exception ex)
{
Fail("write", $"can't write {_path}: {ex.Message}");
try { if (File.Exists(tmp)) File.Delete(tmp); } catch { }
}
}
/// <summary>At most one log line per failure kind.</summary>
private void Fail(string kind, string message)
{
if (_failuresLogged.Add(kind)) _log("[RynthLua] " + message);
}
}

View file

@ -0,0 +1,92 @@
using System;
using System.Runtime.InteropServices;
using MoonSharp.Interpreter;
namespace RynthCore.Plugin.RynthLua;
/// <summary>
/// Library: the built-in <c>require</c> modules and the enum globals (plus Vector2, Vector4
/// and the ImGui enums from LibraryImGuiValues).
///
/// "json" LibraryJson encode / decode
/// "storage" LibraryStorage saved values per script and per character
/// "enums" LibraryEnums ObjectClass, SkillId, ... (also globals)
/// "rynth.ai" LibraryRynthAi.cs RynthAi through RynthAiBridge
/// "filesystem" LibraryFileSystem UB-style file access in the script's data folder
/// "rynthlua" this file the plugin's own info
/// "views" LibraryViews script windows (huds)
/// "imgui" LibraryImGui the ImGui calls a hud's OnRender records
///
/// Any other name leaves <c>module</c> null, so require looks for a file in the script's folder.
/// A module is made once per script state (LuaScriptHost caches it).
/// </summary>
public sealed partial class RynthLuaPlugin
{
/// <summary>Per-script data (storage, filesystem.GetData()): Data\&lt;Script&gt;\.</summary>
internal static string LuaDataRoot => RynthLuaPaths.Data;
/// <summary>Script.Registry key of this script's enums module (the globals can be overwritten by the script, the module can't).</summary>
private const string EnumsRegistryKey = "rynth.enums";
partial void RegisterLibraryGlobals(Script s, ScriptContext ctx)
{
DynValue enums = LibraryEnums.CreateModule(s);
s.Registry.Set(EnumsRegistryKey, enums);
foreach (TablePair p in enums.Table.Pairs)
if (p.Key.Type == DataType.String && p.Value.Type == DataType.Table)
s.Globals.Set(p.Key.String, p.Value);
// MoonSharp's sandbox has its own global json (parse/serialize); replace it with the
// same module require("json") returns, so json.encode works without the require.
s.Globals["json"] = LibraryJson.CreateModule(s);
// Script windows: Vector2, Vector4 and the ImGui enums (ImGuiWindowFlags, ImGuiCol, ...).
LibraryImGuiValues.Register(s);
}
partial void ResolveLibraryModule(Script s, ScriptContext ctx, string name, ref DynValue? module)
{
switch (name.Trim().ToLowerInvariant())
{
case "json":
module = LibraryJson.CreateModule(s);
break;
case "storage":
module = LibraryStorage.CreateModule(s, ctx, LuaDataRoot, CharacterKey);
break;
case "enums":
{
DynValue cached = s.Registry.Get(EnumsRegistryKey);
module = cached.Type == DataType.Table ? cached : LibraryEnums.CreateModule(s);
break;
}
case "rynth.ai":
module = CreateRynthAiModule(s, ctx);
break;
case "filesystem":
module = LibraryFileSystem.CreateModule(s, ctx, LuaDataRoot);
break;
case "rynthlua":
module = CreateInfoModule(s, ctx);
break;
case "views":
module = CreateViewsModule(s, ctx);
break;
case "imgui":
module = CreateImGuiModule(s);
break;
}
}
/// <summary><c>require("rynthlua")</c>: { Name, Version, ScriptName, ScriptFolder, DataFolder }.</summary>
private static DynValue CreateInfoModule(Script s, ScriptContext ctx)
{
var t = new Table(s);
t.Set("Name", DynValue.NewString("RynthLua"));
t.Set("Version", DynValue.NewString(Marshal.PtrToStringAnsi(VersionPointer) ?? string.Empty));
t.Set("ScriptName", DynValue.NewString(ctx.Name));
t.Set("ScriptFolder", ctx.Folder == null ? DynValue.Nil : DynValue.NewString(ctx.Folder));
t.Set("DataFolder", DynValue.NewString(LibraryPaths.ScriptDataFolder(LuaDataRoot, ctx.Name)));
return DynValue.NewTable(t);
}
}

View file

@ -0,0 +1,366 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Text;
using MoonSharp.Interpreter;
namespace RynthCore.Plugin.RynthLua;
/// <summary>
/// <c>require("enums")</c> and the enum globals every script gets, with UtilityBelt's names
/// and numbers: <c>ObjectClass</c>, <c>SkillId</c>, <c>AttributeId</c>, <c>VitalId</c>,
/// <c>CombatMode</c> (numbering from <see cref="LuaEnums"/>, shared with World/Character/
/// Actions), the property ids <c>IntId</c>, <c>Int64Id</c>, <c>FloatId</c>, <c>StringId</c>,
/// <c>BoolId</c>, <c>DataId</c>, <c>InstanceId</c>, <c>ChatType</c> (also as UB's name
/// <c>ChatMessageType</c>), <c>ClientState</c>, and every enum in <see cref="LuaEnumData"/>
/// (ObjectType, EquipMask, MaterialType, ChatChannel, DistanceType, ...).
///
/// Most enums are plain numbers both ways: <c>SkillId.MeleeDefense == 6</c> and
/// <c>SkillId[6] == "MeleeDefense"</c>; names are also found case-insensitively. Numbers get
/// UB's enum helpers through a number metatable: <c>SkillId.Axe:ToNumber()</c>,
/// <c>EquipMask.Head:HasFlags(...)</c>, <c>AddFlags</c>, <c>RemoveFlags</c>.
///
/// The property-id enums other than IntId (<c>Int64Id</c>, <c>FloatId</c>, <c>StringId</c>,
/// <c>BoolId</c>, <c>DataId</c>, <c>InstanceId</c>) and <c>ObjectType</c> are "typed" values
/// instead (<see cref="LuaEnumValues"/>): one table per value, so <c>wo:Value(StringId.Name)</c>
/// can tell a string id from an int id with the same number, and
/// <c>game.World.GetAll(ObjectType.Creature)</c> from an ObjectClass. They print as their name,
/// compare with each other, and have ToNumber / HasFlags / AddFlags / RemoveFlags.
/// <c>ClientState</c> values are the texts <c>game.State</c> returns
/// (<c>ClientState.In_Game == "InGame"</c>), like <c>ActionError</c>.
/// </summary>
internal static class LibraryEnums
{
/// <summary>Enums whose values are typed tables (see the class summary).</summary>
public static readonly HashSet<string> TypedEnums = new(StringComparer.Ordinal)
{
"Int64Id", "FloatId", "StringId", "BoolId", "DataId", "InstanceId", "ObjectType",
};
/// <summary>UB's names that differ from RynthLua's first name for the same number (kept as aliases).</summary>
private static readonly (string Enum, string Name, int Value)[] Aliases =
{
("SkillId", "Undef", 0), ("SkillId", "ThrownWeapons", 12), ("SkillId", "ArmorRepair", 26),
("SkillId", "MissleWeapons", 47), ("AttributeId", "Undef", 0), ("CombatMode", "Invalid", 153),
("ObjectClass", "NumObjectClasses", 43), ("IntId", "MerchandiseObjectTypes", 74),
("IntId", "HookObjectType", 152),
};
/// <summary>UB's ClientState names → the texts game.State returns (the others never occur).</summary>
private static readonly (string Name, string Value)[] ClientStates =
{
("Initial", "Initial"), ("Game_Started", "Game_Started"), ("Character_Select_Screen", "CharacterSelect"),
("Creating_Character", "Creating_Character"), ("Entering_Game", "Entering_Game"),
("PlayerDesc_Received", "PlayerDesc_Received"), ("In_Game", "InGame"), ("Logging_Out", "LoggingOut"),
("Disconnected", "Disconnected"),
};
public static DynValue CreateModule(Script s)
{
LuaEnumValues.InstallNumberHelpers(s);
var m = new Table(s);
void Add(string name, IEnumerable<(string, long)> members)
{
var list = new List<(string, long)>(members);
foreach (var (e, n, v) in Aliases)
if (e == name) list.Add((n, v));
LuaEnumValues.Define(name, list, LuaEnumValues.LooksLikeFlags(list));
m.Set(name, TypedEnums.Contains(name) ? BuildTyped(s, name, list) : Build(s, name, list));
}
var objectClass = new List<(string, long)>(LuaEnums.ObjectClass.Length);
for (int i = 0; i < LuaEnums.ObjectClass.Length; i++) objectClass.Add((LuaEnums.ObjectClass[i], i));
Add("ObjectClass", objectClass);
Add("SkillId", Pairs(LuaEnums.SkillId));
Add("AttributeId", Pairs(LuaEnums.AttributeId));
Add("VitalId", Pairs(LuaEnums.VitalId));
Add("CombatMode", Pairs(LuaEnums.CombatMode));
Add("IntId", Widen(IntIds));
Add("BoolId", Widen(BoolIds));
Add("StringId", Widen(StringIds));
Add("ChatType", Widen(ChatTypes));
foreach (var (name, _, members) in LuaEnumData.All) Add(name, members);
m.Set("ChatMessageType", m.Get("ChatType")); // UB's name, the same table
var states = new Table(s);
foreach (var (n, v) in ClientStates) states.Set(n, DynValue.NewString(v));
var stMeta = new Table(s);
stMeta.Set("__tostring", DynValue.NewCallback((c, a) => DynValue.NewString("enum ClientState")));
states.MetaTable = stMeta;
m.Set("ClientState", DynValue.NewTable(states));
var mt = new Table(s);
mt.Set("__tostring", DynValue.NewCallback((c, a) => DynValue.NewString("module enums")));
m.MetaTable = mt;
return DynValue.NewTable(m);
}
private static IEnumerable<(string, long)> Pairs(Dictionary<string, int> d)
{
var list = new List<(string, long)>(d.Count);
foreach (var kv in d) list.Add((kv.Key, kv.Value));
list.Sort((x, y) => x.Item2.CompareTo(y.Item2));
return list;
}
private static IEnumerable<(string, long)> Widen(IEnumerable<(string, int)> members)
{
foreach (var (n, v) in members) yield return (n, v);
}
/// <summary>Int-valued members (LibraryImGuiValues' ImGui enums): see the long overload.</summary>
internal static DynValue Build(Script s, string enumName, IEnumerable<(string Name, int Value)> members)
=> Build(s, enumName, Widen(members));
/// <summary>A table with name → number and number → name (the first name for a number wins); names are also found case-insensitively. Shared with LibraryImGuiValues.</summary>
internal static DynValue Build(Script s, string enumName, IEnumerable<(string Name, long Value)> members)
{
var t = new Table(s);
var byName = new Dictionary<string, long>(StringComparer.OrdinalIgnoreCase);
foreach (var (name, value) in members)
{
// Number keys as DynValues: MoonSharp's Table.Set(int 0, ...) lands where Lua's
// t[0] never looks (ObjectClass.Unknown is 0).
DynValue number = DynValue.NewNumber(value);
t.Set(name, number);
if (t.RawGet(number) == null) t.Set(number, DynValue.NewString(name));
byName.TryAdd(name, value);
}
var mt = new Table(s);
// Only consulted for keys the table doesn't have: a differently-cased name.
mt.Set("__index", DynValue.NewCallback((c, a) =>
{
DynValue key = a.Count > 1 ? a[1] : DynValue.Nil;
return key.Type == DataType.String && byName.TryGetValue(key.String, out long v) ? DynValue.NewNumber(v) : DynValue.Nil;
}));
mt.Set("__tostring", DynValue.NewCallback((c, a) => DynValue.NewString("enum " + enumName)));
t.MetaTable = mt;
return DynValue.NewTable(t);
}
/// <summary>Like <see cref="Build"/>, but name → typed value (number → name stays a name).</summary>
private static DynValue BuildTyped(Script s, string enumName, IEnumerable<(string Name, long Value)> members)
{
var t = new Table(s);
var byName = new Dictionary<string, long>(StringComparer.OrdinalIgnoreCase);
foreach (var (name, value) in members)
{
t.Set(name, LuaEnumValues.Get(s, enumName, value));
DynValue number = DynValue.NewNumber(value);
if (t.RawGet(number) == null) t.Set(number, DynValue.NewString(name));
byName.TryAdd(name, value);
}
var mt = new Table(s);
mt.Set("__index", DynValue.NewCallback((c, a) =>
{
DynValue key = a.Count > 1 ? a[1] : DynValue.Nil;
return key.Type == DataType.String && byName.TryGetValue(key.String, out long v) ? LuaEnumValues.Get(s, enumName, v) : DynValue.Nil;
}));
mt.Set("__tostring", DynValue.NewCallback((c, a) => DynValue.NewString("enum " + enumName)));
t.MetaTable = mt;
return DynValue.NewTable(t);
}
/// <summary>AC's chat message types (UtilityBelt's ChatMessageType names and values).</summary>
private static readonly (string, int)[] ChatTypes =
{
("Default", 0), ("Speech", 2), ("Tell", 3), ("OutgoingTell", 4), ("System", 5), ("Combat", 6),
("Magic", 7), ("Channels", 8), ("OutgoingChannel", 9), ("Social", 10), ("OutgoingSocial", 11),
("Emote", 12), ("Advancement", 13), ("Abuse", 14), ("Help", 15), ("Appraisal", 16),
("Spellcasting", 17), ("Allegiance", 18), ("Fellowship", 19), ("WorldBroadcast", 20),
("CombatEnemy", 21), ("CombatSelf", 22), ("Recall", 23), ("Craft", 24), ("Salvaging", 25),
("AdminTell", 31),
};
// Property ids, from ACE's PropertyInt / PropertyBool / PropertyString (the same table
// RynthAi's Meta/PropertyNames.cs uses), plus UB's alias IntId.ObjectType = 1.
private static readonly (string, int)[] IntIds =
{
("Undef", 0), ("ItemType", 1), ("CreatureType", 2), ("PaletteTemplate", 3), ("ClothingPriority", 4),
("EncumbranceVal", 5), ("ItemsCapacity", 6), ("ContainersCapacity", 7), ("Mass", 8), ("ValidLocations", 9),
("CurrentWieldedLocation", 10), ("MaxStackSize", 11), ("StackSize", 12), ("StackUnitEncumbrance", 13),
("StackUnitMass", 14), ("StackUnitValue", 15), ("ItemUseable", 16), ("RareId", 17), ("UiEffects", 18),
("Value", 19), ("CoinValue", 20), ("TotalExperience", 21), ("AvailableCharacter", 22),
("TotalSkillCredits", 23), ("AvailableSkillCredits", 24), ("Level", 25), ("AccountRequirements", 26),
("ArmorType", 27), ("ArmorLevel", 28), ("AllegianceCpPool", 29), ("AllegianceRank", 30),
("ChannelsAllowed", 31), ("ChannelsActive", 32), ("Bonded", 33), ("MonarchsRank", 34),
("AllegianceFollowers", 35), ("ResistMagic", 36), ("ResistItemAppraisal", 37), ("ResistLockpick", 38),
("DeprecatedResistRepair", 39), ("CombatMode", 40), ("CurrentAttackHeight", 41), ("CombatCollisions", 42),
("NumDeaths", 43), ("Damage", 44), ("DamageType", 45), ("DefaultCombatStyle", 46), ("AttackType", 47),
("WeaponSkill", 48), ("WeaponTime", 49), ("AmmoType", 50), ("CombatUse", 51), ("ParentLocation", 52),
("PlacementPosition", 53), ("WeaponEncumbrance", 54), ("WeaponMass", 55), ("ShieldValue", 56),
("ShieldEncumbrance", 57), ("MissileInventoryLocation", 58), ("FullDamageType", 59), ("WeaponRange", 60),
("AttackersSkill", 61), ("DefendersSkill", 62), ("AttackersSkillValue", 63), ("AttackersClass", 64),
("Placement", 65), ("CheckpointStatus", 66), ("Tolerance", 67), ("TargetingTactic", 68),
("CombatTactic", 69), ("HomesickTargetingTactic", 70), ("NumFollowFailures", 71), ("FriendType", 72),
("FoeType", 73), ("MerchandiseItemTypes", 74), ("MerchandiseMinValue", 75), ("MerchandiseMaxValue", 76),
("NumItemsSold", 77), ("NumItemsBought", 78), ("MoneyIncome", 79), ("MoneyOutflow", 80),
("MaxGeneratedObjects", 81), ("InitGeneratedObjects", 82), ("ActivationResponse", 83), ("OriginalValue", 84),
("NumMoveFailures", 85), ("MinLevel", 86), ("MaxLevel", 87), ("LockpickMod", 88), ("BoosterEnum", 89),
("BoostValue", 90), ("MaxStructure", 91), ("Structure", 92), ("PhysicsState", 93), ("TargetType", 94),
("RadarBlipColor", 95), ("EncumbranceCapacity", 96), ("LoginTimestamp", 97), ("CreationTimestamp", 98),
("PkLevelModifier", 99), ("GeneratorType", 100), ("AiAllowedCombatStyle", 101), ("LogoffTimestamp", 102),
("GeneratorDestructionType", 103), ("ActivationCreateClass", 104), ("ItemWorkmanship", 105),
("ItemSpellcraft", 106), ("ItemCurMana", 107), ("ItemMaxMana", 108), ("ItemDifficulty", 109),
("ItemAllegianceRankLimit", 110), ("PortalBitmask", 111), ("AdvocateLevel", 112), ("Gender", 113),
("Attuned", 114), ("ItemSkillLevelLimit", 115), ("GateLogic", 116), ("ItemManaCost", 117), ("Logoff", 118),
("Active", 119), ("AttackHeight", 120), ("NumAttackFailures", 121), ("AiCpThreshold", 122),
("AiAdvancementStrategy", 123), ("Version", 124), ("Age", 125), ("VendorHappyMean", 126),
("VendorHappyVariance", 127), ("CloakStatus", 128), ("VitaeCpPool", 129), ("NumServicesSold", 130),
("MaterialType", 131), ("NumAllegianceBreaks", 132), ("ShowableOnRadar", 133), ("PlayerKillerStatus", 134),
("VendorHappyMaxItems", 135), ("ScorePageNum", 136), ("ScoreConfigNum", 137), ("ScoreNumScores", 138),
("DeathLevel", 139), ("AiOptions", 140), ("OpenToEveryone", 141), ("GeneratorTimeType", 142),
("GeneratorStartTime", 143), ("GeneratorEndTime", 144), ("GeneratorEndDestructionType", 145),
("XpOverride", 146), ("NumCrashAndTurns", 147), ("ComponentWarningThreshold", 148), ("HouseStatus", 149),
("HookPlacement", 150), ("HookType", 151), ("HookItemType", 152), ("AiPpThreshold", 153),
("GeneratorVersion", 154), ("HouseType", 155), ("PickupEmoteOffset", 156), ("WeenieIteration", 157),
("WieldRequirements", 158), ("WieldSkillType", 159), ("WieldDifficulty", 160), ("HouseMaxHooksUsable", 161),
("HouseCurrentHooksUsable", 162), ("AllegianceMinLevel", 163), ("AllegianceMaxLevel", 164),
("HouseRelinkHookCount", 165), ("SlayerCreatureType", 166), ("ConfirmationInProgress", 167),
("ConfirmationTypeInProgress", 168), ("TsysMutationData", 169), ("NumItemsInMaterial", 170),
("NumTimesTinkered", 171), ("AppraisalLongDescDecoration", 172), ("AppraisalLockpickSuccessPercent", 173),
("AppraisalPages", 174), ("AppraisalMaxPages", 175), ("AppraisalItemSkill", 176), ("GemCount", 177),
("GemType", 178), ("ImbuedEffect", 179), ("AttackersRawSkillValue", 180), ("ChessRank", 181),
("ChessTotalGames", 182), ("ChessGamesWon", 183), ("ChessGamesLost", 184), ("TypeOfAlteration", 185),
("SkillToBeAltered", 186), ("SkillAlterationCount", 187), ("HeritageGroup", 188),
("TransferFromAttribute", 189), ("TransferToAttribute", 190), ("AttributeTransferCount", 191),
("FakeFishingSkill", 192), ("NumKeys", 193), ("DeathTimestamp", 194), ("PkTimestamp", 195),
("VictimTimestamp", 196), ("HookGroup", 197), ("AllegianceSwearTimestamp", 198),
("HousePurchaseTimestamp", 199), ("RedirectableEquippedArmorCount", 200),
("MeleeDefenseImbuedEffectTypeCache", 201), ("MissileDefenseImbuedEffectTypeCache", 202),
("MagicDefenseImbuedEffectTypeCache", 203), ("ElementalDamageBonus", 204), ("ImbueAttempts", 205),
("ImbueSuccesses", 206), ("CreatureKills", 207), ("PlayerKillsPk", 208), ("PlayerKillsPkl", 209),
("RaresTierOne", 210), ("RaresTierTwo", 211), ("RaresTierThree", 212), ("RaresTierFour", 213),
("RaresTierFive", 214), ("AugmentationStat", 215), ("AugmentationFamilyStat", 216),
("AugmentationInnateFamily", 217), ("AugmentationInnateStrength", 218), ("AugmentationInnateEndurance", 219),
("AugmentationInnateCoordination", 220), ("AugmentationInnateQuickness", 221),
("AugmentationInnateFocus", 222), ("AugmentationInnateSelf", 223), ("AugmentationSpecializeSalvaging", 224),
("AugmentationSpecializeItemTinkering", 225), ("AugmentationSpecializeArmorTinkering", 226),
("AugmentationSpecializeMagicItemTinkering", 227), ("AugmentationSpecializeWeaponTinkering", 228),
("AugmentationExtraPackSlot", 229), ("AugmentationIncreasedCarryingCapacity", 230),
("AugmentationLessDeathItemLoss", 231), ("AugmentationSpellsRemainPastDeath", 232),
("AugmentationCriticalDefense", 233), ("AugmentationBonusXp", 234), ("AugmentationBonusSalvage", 235),
("AugmentationBonusImbueChance", 236), ("AugmentationFasterRegen", 237),
("AugmentationIncreasedSpellDuration", 238), ("AugmentationResistanceFamily", 239),
("AugmentationResistanceSlash", 240), ("AugmentationResistancePierce", 241),
("AugmentationResistanceBlunt", 242), ("AugmentationResistanceAcid", 243),
("AugmentationResistanceFire", 244), ("AugmentationResistanceFrost", 245),
("AugmentationResistanceLightning", 246), ("RaresTierOneLogin", 247), ("RaresTierTwoLogin", 248),
("RaresTierThreeLogin", 249), ("RaresTierFourLogin", 250), ("RaresTierFiveLogin", 251),
("RaresLoginTimestamp", 252), ("RaresTierSix", 253), ("RaresTierSeven", 254), ("RaresTierSixLogin", 255),
("RaresTierSevenLogin", 256), ("ItemAttributeLimit", 257), ("ItemAttributeLevelLimit", 258),
("ItemAttribute2ndLimit", 259), ("ItemAttribute2ndLevelLimit", 260), ("CharacterTitleId", 261),
("NumCharacterTitles", 262), ("ResistanceModifierType", 263), ("FreeTinkersBitfield", 264),
("EquipmentSetId", 265), ("PetClass", 266), ("Lifespan", 267), ("RemainingLifespan", 268),
("UseCreateQuantity", 269), ("WieldRequirements2", 270), ("WieldSkillType2", 271), ("WieldDifficulty2", 272),
("WieldRequirements3", 273), ("WieldSkillType3", 274), ("WieldDifficulty3", 275),
("WieldRequirements4", 276), ("WieldSkillType4", 277), ("WieldDifficulty4", 278), ("Unique", 279),
("SharedCooldown", 280), ("Faction1Bits", 281), ("Faction2Bits", 282), ("Faction3Bits", 283),
("Hatred1Bits", 284), ("Hatred2Bits", 285), ("Hatred3Bits", 286), ("SocietyRankCelhan", 287),
("SocietyRankEldweb", 288), ("SocietyRankRadblo", 289), ("HearLocalSignals", 290),
("HearLocalSignalsRadius", 291), ("Cleaving", 292), ("AugmentationSpecializeGearcraft", 293),
("AugmentationInfusedCreatureMagic", 294), ("AugmentationInfusedItemMagic", 295),
("AugmentationInfusedLifeMagic", 296), ("AugmentationInfusedWarMagic", 297),
("AugmentationCriticalExpertise", 298), ("AugmentationCriticalPower", 299),
("AugmentationSkilledMelee", 300), ("AugmentationSkilledMissile", 301), ("AugmentationSkilledMagic", 302),
("ImbuedEffect2", 303), ("ImbuedEffect3", 304), ("ImbuedEffect4", 305), ("ImbuedEffect5", 306),
("DamageRating", 307), ("DamageResistRating", 308), ("AugmentationDamageBonus", 309),
("AugmentationDamageReduction", 310), ("ImbueStackingBits", 311), ("HealOverTime", 312), ("CritRating", 313),
("CritDamageRating", 314), ("CritResistRating", 315), ("CritDamageResistRating", 316),
("HealingResistRating", 317), ("DamageOverTime", 318), ("ItemMaxLevel", 319), ("ItemXpStyle", 320),
("EquipmentSetExtra", 321), ("AetheriaBitfield", 322), ("HealingBoostRating", 323),
("HeritageSpecificArmor", 324), ("AlternateRacialSkills", 325), ("AugmentationJackOfAllTrades", 326),
("AugmentationResistanceNether", 327), ("AugmentationInfusedVoidMagic", 328), ("WeaknessRating", 329),
("NetherOverTime", 330), ("NetherResistRating", 331), ("LuminanceAward", 332), ("LumAugDamageRating", 333),
("LumAugDamageReductionRating", 334), ("LumAugCritDamageRating", 335), ("LumAugCritReductionRating", 336),
("LumAugSurgeEffectRating", 337), ("LumAugSurgeChanceRating", 338), ("LumAugItemManaUsage", 339),
("LumAugItemManaGain", 340), ("LumAugVitality", 341), ("LumAugHealingRating", 342),
("LumAugSkilledCraft", 343), ("LumAugSkilledSpec", 344), ("LumAugNoDestroyCraft", 345),
("RestrictInteraction", 346), ("OlthoiLootTimestamp", 347), ("OlthoiLootStep", 348),
("UseCreatesContractId", 349), ("DotResistRating", 350), ("LifeResistRating", 351), ("CloakWeaveProc", 352),
("WeaponType", 353), ("MeleeMastery", 354), ("RangedMastery", 355), ("SneakAttackRating", 356),
("RecklessnessRating", 357), ("DeceptionRating", 358), ("CombatPetRange", 359), ("WeaponAuraDamage", 360),
("WeaponAuraSpeed", 361), ("SummoningMastery", 362), ("HeartbeatLifespan", 363),
("UseLevelRequirement", 364), ("LumAugAllSkills", 365), ("UseRequiresSkill", 366),
("UseRequiresSkillLevel", 367), ("UseRequiresSkillSpec", 368), ("UseRequiresLevel", 369),
("GearDamage", 370), ("GearDamageResist", 371), ("GearCrit", 372), ("GearCritResist", 373),
("GearCritDamage", 374), ("GearCritDamageResist", 375), ("GearHealingBoost", 376), ("GearNetherResist", 377),
("GearLifeResist", 378), ("GearMaxHealth", 379), ("Unknown380", 380), ("PKDamageRating", 381),
("PKDamageResistRating", 382), ("GearPKDamageRating", 383), ("GearPKDamageResistRating", 384),
("Unknown385", 385), ("Overpower", 386), ("OverpowerResist", 387), ("GearOverpower", 388),
("GearOverpowerResist", 389), ("Enlightenment", 390), ("PCAPRecordedAutonomousMovement", 8007),
("PCAPRecordedMaxVelocityEstimated", 8030), ("PCAPRecordedPlacement", 8041),
("PCAPRecordedAppraisalPages", 8042), ("PCAPRecordedAppraisalMaxPages", 8043), ("TotalLogins", 9001),
("DeletionTimestamp", 9002), ("CharacterOptions1", 9003), ("CharacterOptions2", 9004), ("LootTier", 9005),
("GeneratorProbability", 9006), ("CurrentLoyaltyAtLastLogoff", 9008),
("CurrentLeadershipAtLastLogoff", 9009), ("AllegianceOfficerRank", 9010), ("HouseRentTimestamp", 9011),
("Hairstyle", 9012), ("VisualClothingPriority", 9013), ("SquelchGlobal", 9014), ("InventoryOrder", 9015),
("ObjectType", 1),
};
private static readonly (string, int)[] BoolIds =
{
("Undef", 0), ("Stuck", 1), ("Open", 2), ("Locked", 3), ("RotProof", 4), ("AllegianceUpdateRequest", 5),
("AiUsesMana", 6), ("AiUseHumanMagicAnimations", 7), ("AllowGive", 8), ("CurrentlyAttacking", 9),
("AttackerAi", 10), ("IgnoreCollisions", 11), ("ReportCollisions", 12), ("Ethereal", 13),
("GravityStatus", 14), ("LightsStatus", 15), ("ScriptedCollision", 16), ("Inelastic", 17),
("Visibility", 18), ("Attackable", 19), ("SafeSpellComponents", 20), ("AdvocateState", 21),
("Inscribable", 22), ("DestroyOnSell", 23), ("UiHidden", 24), ("IgnoreHouseBarriers", 25),
("HiddenAdmin", 26), ("PkWounder", 27), ("PkKiller", 28), ("NoCorpse", 29), ("UnderLifestoneProtection", 30),
("ItemManaUpdatePending", 31), ("GeneratorStatus", 32), ("ResetMessagePending", 33), ("DefaultOpen", 34),
("DefaultLocked", 35), ("DefaultOn", 36), ("OpenForBusiness", 37), ("IsFrozen", 38),
("DealMagicalItems", 39), ("LogoffImDead", 40), ("ReportCollisionsAsEnvironment", 41),
("AllowEdgeSlide", 42), ("AdvocateQuest", 43), ("IsAdmin", 44), ("IsArch", 45), ("IsSentinel", 46),
("IsAdvocate", 47), ("CurrentlyPoweringUp", 48), ("GeneratorEnteredWorld", 49), ("NeverFailCasting", 50),
("VendorService", 51), ("AiImmobile", 52), ("DamagedByCollisions", 53), ("IsDynamic", 54), ("IsHot", 55),
("IsAffecting", 56), ("AffectsAis", 57), ("SpellQueueActive", 58), ("GeneratorDisabled", 59),
("IsAcceptingTells", 60), ("LoggingChannel", 61), ("OpensAnyLock", 62), ("UnlimitedUse", 63),
("GeneratedTreasureItem", 64), ("IgnoreMagicResist", 65), ("IgnoreMagicArmor", 66), ("AiAllowTrade", 67),
("SpellComponentsRequired", 68), ("IsSellable", 69), ("IgnoreShieldsBySkill", 70), ("NoDraw", 71),
("ActivationUntargeted", 72), ("HouseHasGottenPriorityBootPos", 73), ("GeneratorAutomaticDestruction", 74),
("HouseHooksVisible", 75), ("HouseRequiresMonarch", 76), ("HouseHooksEnabled", 77),
("HouseNotifiedHudOfHookCount", 78), ("AiAcceptEverything", 79), ("IgnorePortalRestrictions", 80),
("RequiresBackpackSlot", 81), ("DontTurnOrMoveWhenGiving", 82), ("NpcLooksLikeObject", 83),
("IgnoreCloIcons", 84), ("AppraisalHasAllowedWielder", 85), ("ChestRegenOnClose", 86),
("LogoffInMinigame", 87), ("PortalShowDestination", 88), ("PortalIgnoresPkAttackTimer", 89),
("NpcInteractsSilently", 90), ("Retained", 91), ("IgnoreAuthor", 92), ("Limbo", 93),
("AppraisalHasAllowedActivator", 94), ("ExistedBeforeAllegianceXpChanges", 95), ("IsDeaf", 96),
("IsPsr", 97), ("Invincible", 98), ("Ivoryable", 99), ("Dyable", 100), ("CanGenerateRare", 101),
("CorpseGeneratedRare", 102), ("NonProjectileMagicImmune", 103), ("ActdReceivedItems", 104),
("Unknown105", 105), ("FirstEnterWorldDone", 106), ("RecallsDisabled", 107), ("RareUsesTimer", 108),
("ActdPreorderReceivedItems", 109), ("Afk", 110), ("IsGagged", 111), ("ProcSpellSelfTargeted", 112),
("IsAllegianceGagged", 113), ("EquipmentSetTriggerPiece", 114), ("Uninscribe", 115), ("WieldOnUse", 116),
("ChestClearedWhenClosed", 117), ("NeverAttack", 118), ("SuppressGenerateEffect", 119),
("TreasureCorpse", 120), ("EquipmentSetAddLevel", 121), ("BarberActive", 122), ("TopLayerPriority", 123),
("NoHeldItemShown", 124), ("LoginAtLifestone", 125), ("OlthoiPk", 126), ("Account15Days", 127),
("HadNoVitae", 128), ("NoOlthoiTalk", 129), ("AutowieldLeft", 130), ("LinkedPortalOneSummon", 9001),
("LinkedPortalTwoSummon", 9002), ("HouseEvicted", 9003), ("UntrainedSkills", 9004), ("IsEnvoy", 9005),
("UnspecializedSkills", 9006), ("FreeSkillResetRenewed", 9007), ("FreeAttributeResetRenewed", 9008),
("SkillTemplesTimerReset", 9009), ("FreeMasteryResetRenewed", 9010),
};
private static readonly (string, int)[] StringIds =
{
("Undef", 0), ("Name", 1), ("Title", 2), ("Sex", 3), ("HeritageGroup", 4), ("Template", 5),
("AttackersName", 6), ("Inscription", 7), ("ScribeName", 8), ("VendorsName", 9), ("Fellowship", 10),
("MonarchsName", 11), ("LockCode", 12), ("KeyCode", 13), ("Use", 14), ("ShortDesc", 15), ("LongDesc", 16),
("ActivationTalk", 17), ("UseMessage", 18), ("ItemHeritageGroupRestriction", 19), ("PluralName", 20),
("MonarchsTitle", 21), ("ActivationFailure", 22), ("ScribeAccount", 23), ("TownName", 24),
("CraftsmanName", 25), ("UsePkServerError", 26), ("ScoreCachedText", 27), ("ScoreDefaultEntryFormat", 28),
("ScoreFirstEntryFormat", 29), ("ScoreLastEntryFormat", 30), ("ScoreOnlyEntryFormat", 31),
("ScoreNoEntry", 32), ("Quest", 33), ("GeneratorEvent", 34), ("PatronsTitle", 35), ("HouseOwnerName", 36),
("QuestRestriction", 37), ("AppraisalPortalDestination", 38), ("TinkerName", 39), ("ImbuerName", 40),
("HouseOwnerAccount", 41), ("DisplayName", 42), ("DateOfBirth", 43), ("ThirdPartyApi", 44),
("KillQuest", 45), ("Afk", 46), ("AllegianceName", 47), ("AugmentationAddQuest", 48), ("KillQuest2", 49),
("KillQuest3", 50), ("UseSendsSignal", 51), ("GearPlatingName", 52),
("PCAPRecordedCurrentMotionState", 8006), ("PCAPRecordedServerName", 8031),
("PCAPRecordedCharacterName", 8032), ("AllegianceMotd", 9001), ("AllegianceMotdSetBy", 9002),
("AllegianceSpeakerTitle", 9003), ("AllegianceSeneschalTitle", 9004), ("AllegianceCastellanTitle", 9005),
("GodState", 9006), ("TinkerLog", 9007),
};
}

View file

@ -0,0 +1,156 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using MoonSharp.Interpreter;
namespace RynthCore.Plugin.RynthLua;
/// <summary>
/// <c>require("filesystem")</c>, UtilityBelt's shape, for scripts that keep their own files:
///
/// local fs = require("filesystem").GetData() -- Data\&lt;Script&gt;\ (read/write)
/// local fs = require("filesystem").GetScript() -- the script's own folder (read-only)
/// fs.WriteText(file, text), fs.AppendText(file, text), fs.ReadText(file), fs.ReadLines(file),
/// fs.FileExists(file), fs.DirectoryExists(dir), fs.CreateDirectory(dir), fs.DeleteFile(file),
/// fs.GetFiles([dir]), fs.GetDirectories([dir]) (names relative to the folder)
///
/// Like UB's (ref string error), every call returns its result plus an error message:
/// <c>local text, err = fs.ReadText("notes.txt")</c> gives nil and the reason on failure.
/// Paths are relative to the folder and can never leave it (LibraryPaths.Resolve).
/// UB's GetCustom (any folder, with a prompt) isn't offered.
/// </summary>
internal static class LibraryFileSystem
{
private const long MaxReadBytes = 64L * 1024 * 1024;
public static DynValue CreateModule(Script s, ScriptContext ctx, string dataRoot)
{
var m = new Table(s);
DynValue? data = null, script = null;
m.Set("GetData", DynValue.NewCallback((c, a) =>
data ??= CreateAccess(s, LibraryPaths.ScriptDataFolder(dataRoot, ctx.Name), writable: true, "data folder")));
m.Set("GetScript", DynValue.NewCallback((c, a) =>
{
if (ctx.Folder == null)
throw new ScriptRuntimeException("filesystem.GetScript(): only folder scripts (Scripts\\<Name>\\index.lua) have a script folder; use GetData()");
return script ??= CreateAccess(s, ctx.Folder, writable: false, "script folder");
}));
m.Set("GetCustom", DynValue.NewCallback((c, a) =>
throw new ScriptRuntimeException("filesystem.GetCustom isn't available in RynthLua; use GetData() (the script's data folder)")));
var mt = new Table(s);
mt.Set("__tostring", DynValue.NewCallback((c, a) => DynValue.NewString("module filesystem")));
m.MetaTable = mt;
return DynValue.NewTable(m);
}
private static DynValue CreateAccess(Script s, string root, bool writable, string label)
{
var t = new Table(s);
t.Set("IsApproved", DynValue.True);
t.Set("IsReadOnly", DynValue.NewBoolean(!writable));
DynValue Fail(DynValue failed, string error) => DynValue.NewTuple(failed, DynValue.NewString(error));
DynValue Ok(DynValue v) => DynValue.NewTuple(v, DynValue.Nil);
string Arg(CallbackArguments a, int i) => LuaArgs.Str(LuaArgs.At(LuaArgs.Of(a, t), i));
// Resolves argument 0; for writes also checks the folder is writable.
string? Path0(CallbackArguments a, bool write, bool allowRoot, out string error)
{
if (write && !writable) { error = $"the {label} is read-only; write to require(\"filesystem\").GetData()"; return null; }
string rel = Arg(a, 0);
if (!allowRoot && rel.Trim().Length == 0) { error = "needs a file name"; return null; }
return LibraryPaths.Resolve(root, rel, out error);
}
void Add(string name, DynValue failed, bool write, bool allowRoot, Func<CallbackArguments, string, DynValue> body)
{
t.Set(name, DynValue.NewCallback((c, a) =>
{
string? full = Path0(a, write, allowRoot, out string error);
if (full == null) return Fail(failed, $"{name}: {error}");
try { return Ok(body(a, full)); }
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or NotSupportedException or ArgumentException)
{
return Fail(failed, $"{name}: {ex.Message}");
}
catch (InvalidDataException ex) { return Fail(failed, $"{name}: {ex.Message}"); }
}));
}
Add("ReadText", DynValue.Nil, write: false, allowRoot: false, (a, full) =>
DynValue.NewString(ReadAll(full)));
Add("ReadLines", DynValue.Nil, write: false, allowRoot: false, (a, full) =>
{
var list = new Table(s);
foreach (string line in ReadAll(full).Replace("\r\n", "\n").Split('\n'))
list.Append(DynValue.NewString(line));
// A final newline doesn't make an extra empty line.
int n = list.Length;
if (n > 0 && list.Get(n).String.Length == 0) list.Remove(n);
return DynValue.NewTable(list);
});
Add("WriteText", DynValue.False, write: true, allowRoot: false, (a, full) =>
{
Directory.CreateDirectory(Path.GetDirectoryName(full)!);
string tmp = full + ".tmp";
File.WriteAllText(tmp, Arg(a, 1), new UTF8Encoding(false));
File.Move(tmp, full, overwrite: true);
return DynValue.True;
});
Add("AppendText", DynValue.False, write: true, allowRoot: false, (a, full) =>
{
Directory.CreateDirectory(Path.GetDirectoryName(full)!);
File.AppendAllText(full, Arg(a, 1), new UTF8Encoding(false));
return DynValue.True;
});
Add("FileExists", DynValue.False, write: false, allowRoot: false, (a, full) =>
DynValue.NewBoolean(File.Exists(full)));
Add("DirectoryExists", DynValue.False, write: false, allowRoot: true, (a, full) =>
DynValue.NewBoolean(Directory.Exists(full)));
Add("CreateDirectory", DynValue.False, write: true, allowRoot: true, (a, full) =>
{
Directory.CreateDirectory(full);
return DynValue.True;
});
Add("DeleteFile", DynValue.False, write: true, allowRoot: false, (a, full) =>
{
if (!File.Exists(full)) throw new IOException("no such file");
File.Delete(full);
return DynValue.True;
});
Add("GetFiles", DynValue.Nil, write: false, allowRoot: true, (a, full) =>
Listing(s, root, Directory.Exists(full) ? Directory.GetFiles(full) : Array.Empty<string>()));
Add("GetDirectories", DynValue.Nil, write: false, allowRoot: true, (a, full) =>
Listing(s, root, Directory.Exists(full) ? Directory.GetDirectories(full) : Array.Empty<string>()));
var mt = new Table(s);
mt.Set("__tostring", DynValue.NewCallback((c, a) => DynValue.NewString($"filesystem ({label})")));
t.MetaTable = mt;
return DynValue.NewTable(t);
}
private static string ReadAll(string full)
{
var info = new FileInfo(full);
if (!info.Exists) throw new IOException("no such file");
if (info.Length > MaxReadBytes) throw new InvalidDataException($"the file is over {MaxReadBytes / (1024 * 1024)} MB");
return File.ReadAllText(full, Encoding.UTF8);
}
private static DynValue Listing(Script s, string root, string[] paths)
{
string fullRoot = Path.GetFullPath(root);
var names = new List<string>(paths.Length);
foreach (string p in paths)
{
// Our own temp files stay out of sight.
if (p.EndsWith(".tmp", StringComparison.OrdinalIgnoreCase)) continue;
names.Add(Path.GetRelativePath(fullRoot, p));
}
names.Sort(StringComparer.OrdinalIgnoreCase);
var list = new Table(s);
foreach (string n in names) list.Append(DynValue.NewString(n));
return DynValue.NewTable(list);
}
}

View file

@ -0,0 +1,175 @@
using System;
using System.Globalization;
using MoonSharp.Interpreter;
namespace RynthCore.Plugin.RynthLua;
/// <summary>
/// AC icons in script windows (op level 2). UtilityBelt's shape:
///
/// local tex = views.Huds.GetIconTexture(iconId) -- UB: a ManagedTexture
/// ImGui.Image(tex.TexturePtr, Vector2.new(24, 24)) -- UB passes the texture pointer
///
/// Here a "texture" is a small read-only table naming an icon; TexturePtr is the table itself,
/// so both ImGui.Image(tex, size) and ImGui.Image(tex.TexturePtr, size) work, and a plain
/// number is taken as an icon id. The engine turns it into a real texture (decoded from
/// client_portal.dat, cached) and draws a placeholder until then, or when the icon is missing:
/// no pointer ever comes from a script (design §6.3). RynthLua extras:
/// views.Huds.GetObjectIconTexture(objectOrId) (an item's icon with its underlay and overlay,
/// as AC shows it) and views.Huds.GetSpellIconTexture(spellOrId).
/// </summary>
public sealed partial class RynthLuaPlugin
{
private const string IconTexMetaKey = "rynth.icontex.mt";
private const string IconTexCacheKey = "rynth.icontex.cache";
private const string IconTexCountKey = "rynth.icontex.count";
private const int IconTexCacheMax = 4096;
/// <summary>The engine's op level (UiGetInfo); offline (no engine) it is this recorder's own.</summary>
private int _uiOpLevel = HudFormat.OpLevel;
private static readonly string[] IconKindNames = { "icon", "object", "spell" };
/// <summary>A function that records an op-level-2 op refuses on an engine that would skip it.</summary>
private void RequireOpLevel(string fn)
{
if (_uiOpLevel >= HudFormat.OpLevel) return;
throw new ScriptRuntimeException(
$"ImGui.{fn} needs a newer RynthCore engine (script windows op level {HudFormat.OpLevel}; this engine has {_uiOpLevel})");
}
/// <summary>views.Huds.GetIconTexture / GetObjectIconTexture / GetSpellIconTexture and the UB-only CreateTexture.</summary>
private void AddIconFunctions(Script s, Table huds)
{
huds["GetIconTexture"] = DynValue.NewCallback((c, a) =>
{
DynValue v = LuaArgs.At(LuaArgs.Of(a, huds), 0);
return IconTexture(s, HudFormat.IconKindIcon, IdArg(v, "GetIconTexture", "iconId", allowObject: false));
});
huds["GetObjectIconTexture"] = DynValue.NewCallback((c, a) =>
{
DynValue v = LuaArgs.At(LuaArgs.Of(a, huds), 0);
return IconTexture(s, HudFormat.IconKindObject, IdArg(v, "GetObjectIconTexture", "an object or object id", allowObject: true));
});
huds["GetSpellIconTexture"] = DynValue.NewCallback((c, a) =>
{
DynValue v = LuaArgs.At(LuaArgs.Of(a, huds), 0);
return IconTexture(s, HudFormat.IconKindSpell, IdArg(v, "GetSpellIconTexture", "a spell or spell id", allowObject: true));
});
huds["CreateTexture"] = DynValue.NewCallback((c, a) =>
throw new ScriptRuntimeException("views.Huds.CreateTexture(file) isn't supported: RynthLua windows draw AC icons only (GetIconTexture, GetObjectIconTexture, GetSpellIconTexture)"));
}
/// <summary>
/// An id argument: a whole number 0..0xFFFFFFFF, or (<paramref name="allowObject"/>) a table
/// with a numeric Id (a world object, a spell). Anything else is an error.
/// </summary>
private static uint IdArg(DynValue v, string fn, string what, bool allowObject)
{
double d = double.NaN;
if (v.Type == DataType.Number) d = v.Number;
else if (allowObject && v.Type == DataType.Table)
{
DynValue id = v.Table.Get("Id");
if (id.Type == DataType.Number) d = id.Number;
}
if (double.IsFinite(d) && d >= 0 && d <= uint.MaxValue && Math.Floor(d) == d) return (uint)d;
throw new ScriptRuntimeException($"views.Huds.{fn} needs {what} (a whole number 0 to 0xFFFFFFFF), not {DescribeValue(v)}");
}
/// <summary>The script's texture table for (kind, id), made once and cached per script.</summary>
private static DynValue IconTexture(Script s, byte kind, uint id)
{
DynValue cacheV = s.Registry.Get(IconTexCacheKey);
Table cache;
if (cacheV.Type == DataType.Table) cache = cacheV.Table;
else
{
cache = new Table(s);
s.Registry.Set(IconTexCacheKey, DynValue.NewTable(cache));
}
string cacheKey = kind.ToString(CultureInfo.InvariantCulture) + ":" + id.ToString(CultureInfo.InvariantCulture);
DynValue hit = cache.RawGet(cacheKey) ?? DynValue.Nil;
if (hit.Type == DataType.Table) return hit;
// Bounded: a script asking for thousands of different icons starts a fresh cache.
DynValue countV = s.Registry.Get(IconTexCountKey);
double count = countV.Type == DataType.Number ? countV.Number : 0;
if (count >= IconTexCacheMax)
{
cache = new Table(s);
s.Registry.Set(IconTexCacheKey, DynValue.NewTable(cache));
count = 0;
}
s.Registry.Set(IconTexCountKey, DynValue.NewNumber(count + 1));
var t = new Table(s);
t.Set("Kind", DynValue.NewString(IconKindNames[kind]));
t.Set("Id", DynValue.NewNumber(id));
DynValue self = DynValue.NewTable(t);
t.Set("TexturePtr", self); // UB: ImGui.Image(tex.TexturePtr, size)
DynValue noop = DynValue.NewCallback((c, a) => DynValue.Nil);
t.Set("Dispose", noop); // UB: textures are released by the engine's cache here
t.Set("Release", noop);
t.MetaTable = IconTexMeta(s);
cache.Set(cacheKey, self);
return self;
}
private static Table IconTexMeta(Script s)
{
DynValue cached = s.Registry.Get(IconTexMetaKey);
if (cached.Type == DataType.Table) return cached.Table;
var mt = new Table(s);
mt["__index"] = DynValue.NewCallback((c, a) =>
{
string key = a.Count > 1 ? a[1].CastToString() ?? "" : "";
if (key is "Bitmap" or "Texture")
throw new ScriptRuntimeException($"texture.{key} isn't available in RynthLua (the engine owns the texture); pass the texture to ImGui.Image");
return DynValue.Nil;
});
mt["__newindex"] = DynValue.NewCallback((c, a) =>
throw new ScriptRuntimeException("an icon texture is read-only"));
mt["__tostring"] = DynValue.NewCallback((c, a) =>
{
Table? t = a.Count > 0 && a[0].Type == DataType.Table ? a[0].Table : null;
string kind = t?.RawGet("Kind")?.CastToString() ?? "icon";
double id = t?.RawGet("Id")?.Number ?? 0;
return DynValue.NewString($"IconTexture({kind} 0x{(uint)id:X8})");
});
s.Registry.Set(IconTexMetaKey, DynValue.NewTable(mt));
return mt;
}
/// <summary>
/// ImGui.Image's / ImageButton's texture argument: a texture from views.Huds.Get*IconTexture
/// (or its TexturePtr), or a number = an icon id (UB: below 0x06000000, 0x06000000 is added;
/// the engine does that). 0 draws the placeholder. Anything else is an error.
/// </summary>
private static void IconArg(Script s, DynValue v, string fn, out byte kind, out uint id)
{
if (v.Type == DataType.Number)
{
double d = v.Number;
if (double.IsFinite(d) && d >= 0 && d <= uint.MaxValue && Math.Floor(d) == d)
{
kind = HudFormat.IconKindIcon;
id = (uint)d;
return;
}
}
else if (v.Type == DataType.Table && ReferenceEquals(v.Table.MetaTable, IconTexMeta(s)))
{
string k = v.Table.RawGet("Kind")?.CastToString() ?? "";
int i = Array.IndexOf(IconKindNames, k);
DynValue idV = v.Table.RawGet("Id") ?? DynValue.Nil;
if (i >= 0 && idV.Type == DataType.Number)
{
kind = (byte)i;
id = (uint)idV.Number;
return;
}
}
throw new ScriptRuntimeException(
$"ImGui.{fn}: the texture must come from views.Huds.GetIconTexture / GetObjectIconTexture / GetSpellIconTexture, or be an icon id number, not {DescribeValue(v)}");
}
}

View file

@ -0,0 +1,692 @@
using System;
using System.Collections.Generic;
using System.Numerics;
using MoonSharp.Interpreter;
namespace RynthCore.Plugin.RynthLua;
/// <summary>
/// The imgui module: require("imgui"), also as require("imgui").ImGui. Docs/RYNTHLUA_WINDOWS_DESIGN.md
/// §1.3 lists the Phase 1 functions; §9 the op-level-2 ones (Image, ImageButton, InputInt,
/// InputFloat, DragInt, DragFloat), which need an engine reporting OpLevel 2 (RequireOpLevel).
/// RYNTHLUA.md's table and the LuaLS types list exactly what is here (the offline tests check).
///
/// - Names, argument order and defaults follow ImGui.NET 1.91. ref/out parameters come back as
/// extra return values (changed, v = ImGui.Checkbox("x", v)); Combo's index is 0-based.
/// - Every recording function works only inside a hud's render pass (OnPreRender / OnRender);
/// results come one pass late (the engine replays the list and sends events back).
/// - Value widgets compute the key (KeyOf) first, then take the pending result (Take*), then record
/// with that key; a changed value is written into the list, so it agrees with the engine.
/// - SetNextWindowSize/Pos/SizeConstraints set the hud's header fields (by ImGuiCond), not ops.
/// - GetWindowSize/Pos and GetContentRegionAvail return last frame's geometry (inside a pass);
/// GetTextLineHeight, GetFrameHeight, GetStyle and CalcTextSize use UiGetInfo's metrics and
/// work any time, with defaults until the engine has reported them.
/// - Unknown names raise "ImGui.X isn't supported by RynthLua windows yet".
/// </summary>
public sealed partial class RynthLuaPlugin
{
private const string ImGuiRegistryKey = "rynth.imgui";
/// <summary>PushStyleColor ids the engine replays (§4.2 whitelist), ImGui.NET 1.91.6.1 values.</summary>
private static readonly (string Name, int Id)[] StyleColorWhitelist =
{
("Text", 0), ("TextDisabled", 1), ("ChildBg", 3), ("Border", 5), ("FrameBg", 7), ("CheckMark", 18),
("SliderGrab", 19), ("Button", 21), ("ButtonHovered", 22), ("ButtonActive", 23), ("Header", 24),
("HeaderHovered", 25), ("PlotHistogram", 44),
};
private const uint TreeNodeNoTreePushOnOpen = 8;
private const uint TreeNodeDefaultOpen = 32;
private const uint InputTextEnterReturnsTrue = 64;
private const int DefaultInputTextMax = 256;
private DynValue CreateImGuiModule(Script s)
{
DynValue cached = s.Registry.Get(ImGuiRegistryKey);
if (cached.Type == DataType.Table) return cached;
var im = new Table(s);
// Every function: ImGui.X(...) and ImGui:X(...) both work; anything but a
// ScriptRuntimeException thrown inside becomes one (nothing else leaves a callback).
void Fn(string name, Func<DynValue[], DynValue> body)
{
im[name] = DynValue.NewCallback((c, a) =>
{
try { return body(LuaArgs.Of(a, im)); }
catch (InterpreterException) { throw; }
catch (Exception ex) { throw new ScriptRuntimeException($"ImGui.{name}: {ex.Message}"); }
});
}
// ── Text ────────────────────────────────────────────────────────
Fn("Text", args => { Recording("Text").Text(HudFormat.OpText, TextOf(args)); return DynValue.Nil; });
Fn("TextWrapped", args => { Recording("TextWrapped").Text(HudFormat.OpTextWrapped, TextOf(args)); return DynValue.Nil; });
Fn("TextDisabled", args => { Recording("TextDisabled").Text(HudFormat.OpTextDisabled, TextOf(args)); return DynValue.Nil; });
Fn("BulletText", args => { Recording("BulletText").Text(HudFormat.OpBulletText, TextOf(args)); return DynValue.Nil; });
Fn("SeparatorText", args => { Recording("SeparatorText").Text(HudFormat.OpSeparatorText, TextOf(args)); return DynValue.Nil; });
Fn("TextColored", args =>
{
HudRecorder rec = Recording("TextColored");
uint col = LibraryImGuiValues.ColorU32(LuaArgs.At(args, 0));
rec.TextColored(col, TextOf(args, 1));
return DynValue.Nil;
});
Fn("LabelText", args =>
{
HudRecorder rec = Recording("LabelText");
rec.LabelText(LuaArgs.Str(LuaArgs.At(args, 0)), TextOf(args, 1));
return DynValue.Nil;
});
// ── Layout ──────────────────────────────────────────────────────
Fn("Separator", args => { Recording("Separator").Separator(); return DynValue.Nil; });
Fn("NewLine", args => { Recording("NewLine").NewLine(); return DynValue.Nil; });
Fn("Spacing", args => { Recording("Spacing").Spacing(); return DynValue.Nil; });
Fn("SameLine", args =>
{
HudRecorder rec = Recording("SameLine");
float offset = (float)LuaArgs.Num(LuaArgs.At(args, 0), 0);
float spacing = (float)LuaArgs.Num(LuaArgs.At(args, 1), -1);
rec.SameLine(offset, spacing);
return DynValue.Nil;
});
Fn("Dummy", args =>
{
HudRecorder rec = Recording("Dummy");
SizeArg(args, 0, "Dummy", "size", out float w, out float h);
rec.Dummy(w, h);
return DynValue.Nil;
});
Fn("Indent", args => { Recording("Indent").Indent((float)LuaArgs.Num(LuaArgs.At(args, 0), 0)); return DynValue.Nil; });
Fn("Unindent", args => { Recording("Unindent").Unindent((float)LuaArgs.Num(LuaArgs.At(args, 0), 0)); return DynValue.Nil; });
// ── Buttons ─────────────────────────────────────────────────────
Fn("Button", args =>
{
HudRecorder rec = Recording("Button");
string label = LuaArgs.Str(LuaArgs.At(args, 0));
SizeArg(args, 1, "Button", "size", out float w, out float h); // nil = (0, 0): auto
uint key = rec.KeyOf(label);
bool clicked = TakeClick(rec.Hud!, key);
rec.Button(key, label, w, h, small: false);
return DynValue.NewBoolean(clicked);
});
Fn("SmallButton", args =>
{
HudRecorder rec = Recording("SmallButton");
string label = LuaArgs.Str(LuaArgs.At(args, 0));
uint key = rec.KeyOf(label);
bool clicked = TakeClick(rec.Hud!, key);
rec.Button(key, label, 0, 0, small: true);
return DynValue.NewBoolean(clicked);
});
// ── Values: changed, v ──────────────────────────────────────────
Fn("Checkbox", args =>
{
HudRecorder rec = Recording("Checkbox");
string label = LuaArgs.Str(LuaArgs.At(args, 0));
bool value = LuaArgs.At(args, 1).CastToBool();
uint key = rec.KeyOf(label);
bool changed = TakeBool(rec.Hud!, key, out bool newValue);
if (changed) value = newValue;
rec.Checkbox(key, label, value); // the list carries the new value, so it agrees with the engine
return DynValue.NewTuple(DynValue.NewBoolean(changed), DynValue.NewBoolean(value));
});
Fn("SliderInt", args =>
{
HudRecorder rec = Recording("SliderInt");
string label = LuaArgs.Str(LuaArgs.At(args, 0));
int value = IntArg(LuaArgs.At(args, 1), 0);
int min = IntArg(LuaArgs.At(args, 2), 0);
int max = IntArg(LuaArgs.At(args, 3), 100);
string fmt = LuaArgs.Str(LuaArgs.At(args, 4)); // "" = the engine's "%d"; the engine validates it
uint key = rec.KeyOf(label);
bool changed = TakeInt(rec.Hud!, key, out int newValue);
if (changed) value = newValue;
rec.SliderInt(key, label, value, min, max, fmt);
return DynValue.NewTuple(DynValue.NewBoolean(changed), DynValue.NewNumber(value));
});
Fn("SliderFloat", args =>
{
HudRecorder rec = Recording("SliderFloat");
string label = LuaArgs.Str(LuaArgs.At(args, 0));
double given = LuaArgs.Num(LuaArgs.At(args, 1), 0);
float min = (float)LuaArgs.Num(LuaArgs.At(args, 2), 0);
float max = (float)LuaArgs.Num(LuaArgs.At(args, 3), 1);
string fmt = LuaArgs.Str(LuaArgs.At(args, 4)); // "" = the engine's "%.3f"; the engine validates it
uint key = rec.KeyOf(label);
bool changed = TakeFloat(rec.Hud!, key, out float newValue);
rec.SliderFloat(key, label, changed ? newValue : (float)given, min, max, fmt);
// Unchanged, the script's own number comes back as it was (no float rounding).
return DynValue.NewTuple(DynValue.NewBoolean(changed), DynValue.NewNumber(changed ? newValue : given));
});
Fn("InputText", args =>
{
HudRecorder rec = Recording("InputText");
string label = LuaArgs.Str(LuaArgs.At(args, 0));
string text = LuaArgs.Str(LuaArgs.At(args, 1));
int maxLen = IntArg(LuaArgs.At(args, 2), DefaultInputTextMax);
uint flags = FlagsArg(LuaArgs.At(args, 3));
uint key = rec.KeyOf(label);
bool changed = false;
if (TakeText(rec.Hud!, key, out string newText, out bool submitted))
{
// ImGui.NET updates the ref string on every edit; with EnterReturnsTrue only the
// return value waits for Enter.
text = newText;
changed = (flags & InputTextEnterReturnsTrue) == 0 || submitted;
}
rec.InputText(key, label, text, maxLen, flags);
return DynValue.NewTuple(DynValue.NewBoolean(changed), DynValue.NewString(text));
});
Fn("Combo", args =>
{
HudRecorder rec = Recording("Combo");
string label = LuaArgs.Str(LuaArgs.At(args, 0));
int index = IntArg(LuaArgs.At(args, 1), 0);
List<string> items = ComboItems(LuaArgs.At(args, 2), LuaArgs.At(args, 3));
uint key = rec.KeyOf(label);
bool changed = TakeInt(rec.Hud!, key, out int newIndex);
if (changed) index = newIndex;
rec.Combo(key, label, index, items);
return DynValue.NewTuple(DynValue.NewBoolean(changed), DynValue.NewNumber(index));
});
Fn("Selectable", args =>
{
HudRecorder rec = Recording("Selectable");
string label = LuaArgs.Str(LuaArgs.At(args, 0));
bool selected = LuaArgs.At(args, 1).CastToBool();
uint flags = FlagsArg(LuaArgs.At(args, 2));
SizeArg(args, 3, "Selectable", "size", out float w, out float h);
uint key = rec.KeyOf(label);
bool clicked = TakeClick(rec.Hud!, key);
// The list carries the selected state the script passed: the usual value form
// (Selectable(name, sel == i)) sets its own state from the click next pass.
rec.Selectable(key, label, selected, flags, w, h);
// UB's ref form: clicked, selected (toggled by the click). `if Selectable(...)` still works.
return DynValue.NewTuple(DynValue.NewBoolean(clicked), DynValue.NewBoolean(clicked ? !selected : selected));
});
// ── Numbers (op level 2): changed, v ────────────────────────────
Fn("InputInt", args =>
{
HudRecorder rec = Recording("InputInt");
RequireOpLevel("InputInt");
string label = LuaArgs.Str(LuaArgs.At(args, 0));
int value = IntArg(LuaArgs.At(args, 1), 0);
int step = IntArg(LuaArgs.At(args, 2), 1); // ImGui.NET's defaults
int stepFast = IntArg(LuaArgs.At(args, 3), 100);
uint flags = FlagsArg(LuaArgs.At(args, 4));
uint key = rec.KeyOf(label);
bool changed = TakeInt(rec.Hud!, key, out int newValue);
if (changed) value = newValue;
rec.InputInt(key, label, value, step, stepFast, flags);
return DynValue.NewTuple(DynValue.NewBoolean(changed), DynValue.NewNumber(value));
});
Fn("InputFloat", args =>
{
HudRecorder rec = Recording("InputFloat");
RequireOpLevel("InputFloat");
string label = LuaArgs.Str(LuaArgs.At(args, 0));
double given = LuaArgs.Num(LuaArgs.At(args, 1), 0);
float step = (float)LuaArgs.Num(LuaArgs.At(args, 2), 0);
float stepFast = (float)LuaArgs.Num(LuaArgs.At(args, 3), 0);
string fmt = LuaArgs.Str(LuaArgs.At(args, 4)); // "" = the engine's "%.3f"; the engine validates it
uint flags = FlagsArg(LuaArgs.At(args, 5));
uint key = rec.KeyOf(label);
bool changed = TakeFloat(rec.Hud!, key, out float newValue);
rec.InputFloat(key, label, changed ? newValue : (float)given, step, stepFast, fmt, flags);
return DynValue.NewTuple(DynValue.NewBoolean(changed), DynValue.NewNumber(changed ? newValue : given));
});
Fn("DragInt", args =>
{
HudRecorder rec = Recording("DragInt");
RequireOpLevel("DragInt");
string label = LuaArgs.Str(LuaArgs.At(args, 0));
int value = IntArg(LuaArgs.At(args, 1), 0);
float speed = (float)LuaArgs.Num(LuaArgs.At(args, 2), 1);
int min = IntArg(LuaArgs.At(args, 3), 0); // min == max: no bounds (ImGui)
int max = IntArg(LuaArgs.At(args, 4), 0);
string fmt = LuaArgs.Str(LuaArgs.At(args, 5)); // "" = the engine's "%d"
uint flags = FlagsArg(LuaArgs.At(args, 6)); // ImGuiSliderFlags
uint key = rec.KeyOf(label);
bool changed = TakeInt(rec.Hud!, key, out int newValue);
if (changed) value = newValue;
rec.DragInt(key, label, value, speed, min, max, fmt, flags);
return DynValue.NewTuple(DynValue.NewBoolean(changed), DynValue.NewNumber(value));
});
Fn("DragFloat", args =>
{
HudRecorder rec = Recording("DragFloat");
RequireOpLevel("DragFloat");
string label = LuaArgs.Str(LuaArgs.At(args, 0));
double given = LuaArgs.Num(LuaArgs.At(args, 1), 0);
float speed = (float)LuaArgs.Num(LuaArgs.At(args, 2), 1);
float min = (float)LuaArgs.Num(LuaArgs.At(args, 3), 0);
float max = (float)LuaArgs.Num(LuaArgs.At(args, 4), 0);
string fmt = LuaArgs.Str(LuaArgs.At(args, 5)); // "" = the engine's "%.3f"
uint flags = FlagsArg(LuaArgs.At(args, 6)); // ImGuiSliderFlags
uint key = rec.KeyOf(label);
bool changed = TakeFloat(rec.Hud!, key, out float newValue);
rec.DragFloat(key, label, changed ? newValue : (float)given, speed, min, max, fmt, flags);
return DynValue.NewTuple(DynValue.NewBoolean(changed), DynValue.NewNumber(changed ? newValue : given));
});
// ── Icons (op level 2) ──────────────────────────────────────────
Fn("Image", args =>
{
HudRecorder rec = Recording("Image");
RequireOpLevel("Image");
IconArg(s, LuaArgs.At(args, 0), "Image", out byte kind, out uint id);
IconSizeArg(args, 1, "Image", out float w, out float h);
Vector2 uv0 = OptVec(args, 2, "Image", "uv0", Vector2.Zero);
Vector2 uv1 = OptVec(args, 3, "Image", "uv1", Vector2.One);
uint tint = OptColor(args, 4, 0xFFFFFFFF);
uint border = OptColor(args, 5, 0);
rec.Image(kind, id, w, h, uv0, uv1, tint, border);
return DynValue.Nil;
});
Fn("ImageButton", args =>
{
HudRecorder rec = Recording("ImageButton");
RequireOpLevel("ImageButton");
string strId = LuaArgs.Str(LuaArgs.At(args, 0));
IconArg(s, LuaArgs.At(args, 1), "ImageButton", out byte kind, out uint id);
IconSizeArg(args, 2, "ImageButton", out float w, out float h);
Vector2 uv0 = OptVec(args, 3, "ImageButton", "uv0", Vector2.Zero);
Vector2 uv1 = OptVec(args, 4, "ImageButton", "uv1", Vector2.One);
uint bg = OptColor(args, 5, 0);
uint tint = OptColor(args, 6, 0xFFFFFFFF);
uint key = rec.KeyOf(strId);
bool clicked = TakeClick(rec.Hud!, key);
rec.ImageButton(key, strId, kind, id, w, h, uv0, uv1, bg, tint);
return DynValue.NewBoolean(clicked);
});
// ── Display ─────────────────────────────────────────────────────
Fn("ProgressBar", args =>
{
HudRecorder rec = Recording("ProgressBar");
float fraction = (float)LuaArgs.Num(LuaArgs.At(args, 0), 0);
float w = -1, h = 0; // ImGui's default: fill the width, frame height
if (!LuaArgs.At(args, 1).IsNil()) SizeArg(args, 1, "ProgressBar", "size", out w, out h);
DynValue overlay = LuaArgs.At(args, 2);
rec.ProgressBar(fraction, w, h, overlay.IsNil() ? string.Empty : overlay.ToPrintString()); // "" = ImGui's percentage
return DynValue.Nil;
});
// ── Containers ──────────────────────────────────────────────────
Fn("BeginChild", args =>
{
HudRecorder rec = Recording("BeginChild");
string id = LuaArgs.At(args, 0).IsNil() ? string.Empty : LuaArgs.At(args, 0).ToPrintString();
SizeArg(args, 1, "BeginChild", "size", out float w, out float h);
DynValue b = LuaArgs.At(args, 2);
// A boolean (the old `border` overload) or ImGuiChildFlags (Borders = bit0).
bool border = b.Type == DataType.Boolean ? b.Boolean : (FlagsArg(b) & 1) != 0;
uint windowFlags = FlagsArg(LuaArgs.At(args, 3));
uint key = rec.KeyOf(id);
rec.BeginChild(key, id, w, h, border, windowFlags);
return DynValue.True; // EndChild is always required (ImGui.NET semantics)
});
Fn("EndChild", args => { Recording("EndChild").EndChild(); return DynValue.Nil; });
Fn("CollapsingHeader", args =>
{
HudRecorder rec = Recording("CollapsingHeader");
string label = LuaArgs.Str(LuaArgs.At(args, 0));
if (LuaArgs.At(args, 1).Type == DataType.Boolean)
throw new ScriptRuntimeException("ImGui.CollapsingHeader(label, visible) isn't supported yet; use CollapsingHeader(label [, flags])");
// A header never pushes (NoTreePushOnOpen is part of what a header is).
uint flags = FlagsArg(LuaArgs.At(args, 1)) & ~TreeNodeNoTreePushOnOpen;
uint key = rec.KeyOf(label);
bool open = GetOpenState(rec.Hud!, key, (flags & TreeNodeDefaultOpen) != 0);
rec.CollapsingHeader(key, label, flags, open);
return DynValue.NewBoolean(open);
});
Fn("TreeNode", args =>
{
HudRecorder rec = Recording("TreeNode");
string label = LuaArgs.Str(LuaArgs.At(args, 0));
uint flags = FlagsArg(LuaArgs.At(args, 1));
// The engine owns TreePop, and the recorder expects one for every open node, so a node
// that doesn't push can't be expressed yet.
if ((flags & TreeNodeNoTreePushOnOpen) != 0)
throw new ScriptRuntimeException("ImGui.TreeNode: the NoTreePushOnOpen flag isn't supported yet (TreePop is always needed after an open node)");
uint key = rec.KeyOf(label);
bool open = GetOpenState(rec.Hud!, key, (flags & TreeNodeDefaultOpen) != 0);
rec.TreeNode(key, label, flags, open); // recorded closed: the recorder closes the block itself
return DynValue.NewBoolean(open);
});
Fn("TreePop", args => { Recording("TreePop").TreePop(); return DynValue.Nil; });
// ── IDs and style ───────────────────────────────────────────────
Fn("PushID", args =>
{
HudRecorder rec = Recording("PushID");
DynValue v = LuaArgs.At(args, 0);
if (v.Type == DataType.Number && IntegerId(v.Number, out int n)) rec.PushID(n);
else if (v.Type is DataType.Number or DataType.String) rec.PushID(v.ToPrintString());
else throw new ScriptRuntimeException($"ImGui.PushID needs a string or a number, not {v.Type.ToLuaTypeString()}");
return DynValue.Nil;
});
Fn("PopID", args => { Recording("PopID").PopID(); return DynValue.Nil; });
Fn("PushStyleColor", args =>
{
HudRecorder rec = Recording("PushStyleColor");
int id = StyleColorId(LuaArgs.At(args, 0));
uint col = LibraryImGuiValues.ColorU32(LuaArgs.At(args, 1));
rec.PushStyleColor(id, col);
return DynValue.Nil;
});
Fn("PopStyleColor", args => { Recording("PopStyleColor").PopStyleColor(IntArg(LuaArgs.At(args, 0), 1)); return DynValue.Nil; });
// ── Tooltips ────────────────────────────────────────────────────
Fn("SetItemTooltip", args => { Recording("SetItemTooltip").SetItemTooltip(TextOf(args)); return DynValue.Nil; });
// ── Window (OnPreRender or OnRender): hud header fields, not ops ──
Fn("SetNextWindowSize", args =>
{
ScriptHud hud = Recording("SetNextWindowSize").Hud!;
Vector2 size = VecArg(args, 0, "SetNextWindowSize", "size");
int cond = IntArg(LuaArgs.At(args, 1), CondNone);
if (IsFirstUseEver(cond))
{
// A default size: used by the engine only when nothing is saved for the window.
size = Finite(size); // the header sends non-finite as 0 (= the engine default)
if (hud.DefaultSize != size) { hud.DefaultSize = size; hud.PropsDirty = true; }
}
else if (CondFires(hud, cond))
{
// A per-pass request (reset before every pass); SubmitHuds' header compare sends a change.
hud.RequestSize = size;
}
return DynValue.Nil;
});
Fn("SetNextWindowPos", args =>
{
ScriptHud hud = Recording("SetNextWindowPos").Hud!;
Vector2 pos = VecArg(args, 0, "SetNextWindowPos", "pos");
int cond = IntArg(LuaArgs.At(args, 1), CondNone);
// args[2] (pivot) is accepted and ignored in the MVP.
if (IsFirstUseEver(cond))
{
hud.RequestPos = pos;
hud.PosIsDefault = true; // a default position, not a request
}
else if (CondFires(hud, cond))
{
hud.RequestPos = pos;
hud.PosIsDefault = false;
}
return DynValue.Nil;
});
Fn("SetNextWindowSizeConstraints", args =>
{
ScriptHud hud = Recording("SetNextWindowSizeConstraints").Hud!;
Vector2 min = VecArg(args, 0, "SetNextWindowSizeConstraints", "min");
VecArg(args, 1, "SetNextWindowSizeConstraints", "max");
// MVP: only the minimum maps onto the panel (MinSize, persistent); the maximum is
// checked for shape and ignored, as the panel host has no maximum size.
min = Finite(min);
if (hud.MinSize != min) { hud.MinSize = min; hud.PropsDirty = true; }
return DynValue.Nil;
});
// ── Queries: last frame's window geometry (inside a pass) ───────
// (0, 0) until the first Geometry event (0 = auto in every size argument).
Fn("GetWindowSize", args => Vec2(s, Recording("GetWindowSize").Hud!.Geometry.WindowSize));
Fn("GetWindowPos", args => Vec2(s, Recording("GetWindowPos").Hud!.Geometry.WindowPos));
Fn("GetContentRegionAvail", args => Vec2(s, Recording("GetContentRegionAvail").Hud!.Geometry.ContentAvail));
// ── Metrics (UiGetInfo; any time, logical units) ────────────────
Fn("GetTextLineHeight", args => { RefreshUiInfo(force: false); return DynValue.NewNumber(_uiLineHeight); });
Fn("GetTextLineHeightWithSpacing", args => { RefreshUiInfo(force: false); return DynValue.NewNumber(_uiLineHeight + _uiSpacingY); });
Fn("GetFrameHeight", args => { RefreshUiInfo(force: false); return DynValue.NewNumber(_uiFrameHeight); });
Fn("GetStyle", args =>
{
RefreshUiInfo(force: false);
var style = new Table(s);
style["ItemSpacing"] = LibraryImGuiValues.NewVec2(s, _uiSpacingX, _uiSpacingY);
style["FramePadding"] = LibraryImGuiValues.NewVec2(s, _uiPaddingX, _uiPaddingY);
var styleMt = new Table(s);
styleMt["__index"] = DynValue.NewCallback((c, a) =>
{
string key = a.Count > 1 ? a[1].CastToString() ?? "?" : "?";
throw new ScriptRuntimeException($"ImGui.GetStyle().{key} isn't supported by RynthLua windows yet (ItemSpacing and FramePadding are)");
});
style.MetaTable = styleMt;
return DynValue.NewTable(style);
});
Fn("CalcTextSize", args =>
{
RefreshUiInfo(force: false);
string text = LuaArgs.At(args, 0).IsNil() ? string.Empty : LuaArgs.At(args, 0).ToPrintString();
bool hideAfterDoubleHash = LuaArgs.At(args, 1).CastToBool();
// args[2] (wrapWidth) is ignored in the MVP.
Vector2 size = CalcTextSize(text, hideAfterDoubleHash);
return LibraryImGuiValues.NewVec2(s, size.X, size.Y);
});
im["ImGui"] = DynValue.NewTable(im); // require("imgui").ImGui works too
var mt = new Table(s);
mt["__index"] = DynValue.NewCallback((c, a) =>
{
string key = a.Count > 1 ? a[1].CastToString() ?? "?" : "?";
throw new ScriptRuntimeException($"ImGui.{key} isn't supported by RynthLua windows yet");
});
im.MetaTable = mt;
DynValue module = DynValue.NewTable(im);
s.Registry.Set(ImGuiRegistryKey, module);
return module;
}
/// <summary>The recorder of the pass in progress; ImGui calls outside a pass are an error.</summary>
private HudRecorder Recording(string fn)
{
if (_recorder.Hud == null)
throw new ScriptRuntimeException($"ImGui.{fn}: ImGui calls only work inside a hud's OnRender");
return _recorder;
}
/// <summary>The arguments from <paramref name="from"/> on, concatenated (Text("a", 1) = "a1").</summary>
private static string TextOf(DynValue[] args, int from = 0)
{
int n = args.Length - from;
if (n <= 1) return LuaArgs.At(args, from).ToPrintString();
var parts = new string[n];
for (int i = 0; i < n; i++) parts[i] = args[from + i].ToPrintString();
return string.Concat(parts);
}
// ── Window calls and queries ────────────────────────────────────────
// ImGuiCond (ImGui.NET 1.91.6.1)
private const int CondNone = 0, CondAlways = 1, CondOnce = 2, CondFirstUseEver = 4, CondAppearing = 8;
/// <summary>FirstUseEver (without Always): a default the engine uses only when nothing is saved.</summary>
private static bool IsFirstUseEver(int cond) => (cond & CondFirstUseEver) != 0 && (cond & CondAlways) == 0;
/// <summary>
/// Whether a SetNextWindow* request applies this pass: None/Always every pass; Appearing on the
/// first pass since the hud was shown; Once until the hud's first good pass.
/// </summary>
private static bool CondFires(ScriptHud hud, int cond)
{
if (cond == CondNone || (cond & CondAlways) != 0) return true;
if ((cond & CondAppearing) != 0 && hud.FirstPassSinceShown) return true;
if ((cond & CondOnce) != 0 && !hud.EverPassed) return true;
return false;
}
private static Vector2 Finite(Vector2 v) => new(float.IsFinite(v.X) ? v.X : 0f, float.IsFinite(v.Y) ? v.Y : 0f);
private static DynValue Vec2(Script s, Vector2 v) => LibraryImGuiValues.NewVec2(s, v.X, v.Y);
/// <summary>A required Vector2 argument (Vector2, {x, y} or {X=, Y=}).</summary>
private static Vector2 VecArg(DynValue[] args, int i, string fn, string what)
{
DynValue v = LuaArgs.At(args, i);
if (LibraryImGuiValues.TryVec2(v, out float x, out float y)) return new Vector2(x, y);
throw new ScriptRuntimeException($"ImGui.{fn}: {what} must be a Vector2 or {{x, y}}, not {v.Type.ToLuaTypeString()}");
}
/// <summary>
/// CalcTextSize from UiGetInfo's default-font advances: exact for ASCII 32..126; any other
/// character counts as the mean advance of 'a'..'z' (an estimate), a tab as four spaces.
/// Lines split on \n (\r is skipped, as ImGui does): the width is the longest line, rounded up
/// in pixels as ImGui does; the height is the line count times the line height. Logical units.
/// </summary>
private Vector2 CalcTextSize(string text, bool hideAfterDoubleHash)
{
if (hideAfterDoubleHash)
{
int cut = text.IndexOf("##", StringComparison.Ordinal);
if (cut >= 0) text = text[..cut];
}
float[] adv = _uiAdvancePx;
float mean = 0;
for (int c = 'a'; c <= 'z'; c++) mean += adv[c - ' '];
mean /= 26;
float widest = 0, line = 0;
int newlines = 0;
foreach (char ch in text)
{
if (ch == '\n')
{
widest = Math.Max(widest, line);
line = 0;
newlines++;
continue;
}
if (ch == '\r' || char.IsLowSurrogate(ch)) continue; // a surrogate pair counts once
line += ch is >= ' ' and <= '~' ? adv[ch - ' '] : ch == '\t' ? 4 * adv[0] : mean;
}
widest = Math.Max(widest, line);
// ImGui: a trailing empty line after the last \n adds no height; an empty text is one line.
int lines = newlines + (line > 0 || newlines == 0 ? 1 : 0);
float widthPx = MathF.Truncate(widest + 0.99999f);
return new Vector2(widthPx / _uiScale, lines * _uiLineHeight);
}
// ── Argument helpers ────────────────────────────────────────────────
/// <summary>A size: Vector2, {x, y} or {X=, Y=}; nil = (0, 0); anything else is an error.</summary>
private static void SizeArg(DynValue[] args, int i, string fn, string what, out float w, out float h)
{
DynValue v = LuaArgs.At(args, i);
if (LibraryImGuiValues.TryVec2(v, out w, out h)) return;
if (v.IsNil()) return;
throw new ScriptRuntimeException($"ImGui.{fn}: {what} must be a Vector2 or {{x, y}}, not {v.Type.ToLuaTypeString()}");
}
/// <summary>The icon size AC draws when the script gives none (RynthLua extra: ImGui.NET requires a size).</summary>
private const float DefaultIconSize = 32f;
/// <summary>An icon's size: a Vector2 or {x, y}; nil = 32 x 32 (the size AC's icons are).</summary>
private static void IconSizeArg(DynValue[] args, int i, string fn, out float w, out float h)
{
if (LuaArgs.At(args, i).IsNil()) { w = h = DefaultIconSize; return; }
SizeArg(args, i, fn, "size", out w, out h);
}
/// <summary>An optional Vector2 argument; nil = <paramref name="fallback"/>, another type is an error.</summary>
private static Vector2 OptVec(DynValue[] args, int i, string fn, string what, Vector2 fallback) =>
LuaArgs.At(args, i).IsNil() ? fallback : VecArg(args, i, fn, what);
/// <summary>An optional colour (Vector4 0..1 or 0xAABBGGRR); nil = <paramref name="fallback"/>.</summary>
private static uint OptColor(DynValue[] args, int i, uint fallback) =>
LuaArgs.At(args, i).IsNil() ? fallback : LibraryImGuiValues.ColorU32(LuaArgs.At(args, i));
/// <summary>A number as an int (truncated, clamped to the int range); nil or NaN = <paramref name="fallback"/>.</summary>
private static int IntArg(DynValue v, int fallback)
{
double d = LuaArgs.Num(v, fallback);
if (double.IsNaN(d)) return fallback;
return (int)Math.Clamp(Math.Truncate(d), int.MinValue, int.MaxValue);
}
/// <summary>A flags number as a u32 (a negative int wraps, as a C# enum cast would); nil = 0.</summary>
private static uint FlagsArg(DynValue v)
{
double d = LuaArgs.Num(v, 0);
if (!double.IsFinite(d)) return 0;
d = Math.Truncate(d);
if (d >= 0) return d >= uint.MaxValue ? uint.MaxValue : (uint)d;
return unchecked((uint)(int)Math.Max(d, int.MinValue));
}
/// <summary>
/// PushID's int form: an integer in the int range, or in the u32 range (object ids above
/// 0x7FFFFFFF wrap, as C#'s unchecked (int) cast does). Anything else uses the string form.
/// </summary>
private static bool IntegerId(double d, out int n)
{
n = 0;
if (!double.IsFinite(d) || Math.Floor(d) != d || d < int.MinValue || d > uint.MaxValue) return false;
n = unchecked((int)(long)d);
return true;
}
/// <summary>An ImGuiCol id (number, or a whitelisted name) that the engine replays; others are an error.</summary>
private static int StyleColorId(DynValue v)
{
if (v.Type == DataType.Number && double.IsFinite(v.Number))
{
foreach (var (_, id) in StyleColorWhitelist)
if (id == v.Number) return id;
}
else if (v.Type == DataType.String)
{
foreach (var (name, id) in StyleColorWhitelist)
if (string.Equals(name, v.String, StringComparison.OrdinalIgnoreCase)) return id;
}
var names = new string[StyleColorWhitelist.Length];
for (int i = 0; i < names.Length; i++) names[i] = StyleColorWhitelist[i].Name;
throw new ScriptRuntimeException(
$"ImGui.PushStyleColor: colour {v.ToPrintString()} isn't supported; use ImGuiCol.{string.Join(", ", names)}");
}
/// <summary>
/// Combo items: a Lua array (1-based; <paramref name="count"/> limits how many are used) or
/// ImGui's "a\0b\0c\0" string (ending at the first empty item; its optional 4th argument is
/// ImGui.NET's popup height, which is ignored). At most 512 items are kept.
/// </summary>
private static List<string> ComboItems(DynValue items, DynValue count)
{
var list = new List<string>();
if (items.Type == DataType.Table)
{
int n = items.Table.Length;
if (!count.IsNil()) n = Math.Min(n, Math.Max(0, IntArg(count, n)));
n = Math.Min(n, HudFormat.MaxComboItems);
for (int i = 1; i <= n; i++)
{
DynValue it = items.Table.Get(i);
list.Add(it.IsNil() ? string.Empty : it.ToPrintString());
}
}
else if (items.Type == DataType.String)
{
string all = items.String;
int start = 0;
while (start < all.Length && list.Count < HudFormat.MaxComboItems)
{
int end = all.IndexOf('\0', start);
if (end < 0) end = all.Length;
if (end == start) break; // an empty item ends the list ("\0\0")
list.Add(all[start..end]);
start = end + 1;
}
}
else if (!items.IsNil())
{
throw new ScriptRuntimeException($"ImGui.Combo: items must be a table of strings or a \"\\0\"-separated string, not {items.Type.ToLuaTypeString()}");
}
return list;
}
}

View file

@ -0,0 +1,350 @@
using System;
using System.Globalization;
using MoonSharp.Interpreter;
namespace RynthCore.Plugin.RynthLua;
/// <summary>
/// The value globals the imgui module works with (Docs/RYNTHLUA_WINDOWS_DESIGN.md §1.3):
///
/// Vector2.new(x, y), Vector2(x, y) a table { X, Y } (x / y also read and write)
/// Vector4.new(x, y, z, w), Vector4(...) a table { X, Y, Z, W }
/// Vector2.Zero / One, Vector4.Zero / One fresh values each time
/// + - * / and unary -, == and tostring (* and / take a number or a vector)
///
/// and the ImGui enums with ImGui.NET 1.91.6.1's names and values: ImGuiWindowFlags, ImGuiCond,
/// ImGuiCol, ImGuiTreeNodeFlags, ImGuiInputTextFlags, ImGuiSelectableFlags, ImGuiChildFlags,
/// ImGuiSliderFlags (DragInt / DragFloat)
/// (the same two-way, case-insensitive tables as the other enum globals).
///
/// Every script gets its own tables; the vector metatables live in its Script.Registry.
/// The helpers (TryVec2, TryVec4, ColorU32, NewVec2) are for the imgui functions.
/// </summary>
internal static class LibraryImGuiValues
{
private const string Vec2MetaKey = "rynth.vec2mt";
private const string Vec4MetaKey = "rynth.vec4mt";
private static readonly string[] Upper = { "X", "Y", "Z", "W" };
/// <summary>Sets the Vector2 / Vector4 constructors and the ImGui enums as globals of <paramref name="s"/>.</summary>
public static void Register(Script s)
{
s.Globals["Vector2"] = Constructor(s, 2);
s.Globals["Vector4"] = Constructor(s, 4);
s.Globals["ImGuiWindowFlags"] = LibraryEnums.Build(s, "ImGuiWindowFlags", WindowFlags);
s.Globals["ImGuiCond"] = LibraryEnums.Build(s, "ImGuiCond", Cond);
s.Globals["ImGuiCol"] = LibraryEnums.Build(s, "ImGuiCol", Col);
s.Globals["ImGuiTreeNodeFlags"] = LibraryEnums.Build(s, "ImGuiTreeNodeFlags", TreeNodeFlags);
s.Globals["ImGuiInputTextFlags"] = LibraryEnums.Build(s, "ImGuiInputTextFlags", InputTextFlags);
s.Globals["ImGuiSelectableFlags"] = LibraryEnums.Build(s, "ImGuiSelectableFlags", SelectableFlags);
s.Globals["ImGuiChildFlags"] = LibraryEnums.Build(s, "ImGuiChildFlags", ChildFlags);
s.Globals["ImGuiSliderFlags"] = LibraryEnums.Build(s, "ImGuiSliderFlags", SliderFlags);
}
// ── Vectors ─────────────────────────────────────────────────────────
public static DynValue NewVec2(Script s, float x, float y) => NewVec(s, 2, x, y, 0, 0);
public static DynValue NewVec4(Script s, float x, float y, float z, float w) => NewVec(s, 4, x, y, z, w);
private static DynValue NewVec(Script s, int dim, double x, double y, double z, double w)
{
var t = new Table(s);
t.Set("X", DynValue.NewNumber(x));
t.Set("Y", DynValue.NewNumber(y));
if (dim == 4)
{
t.Set("Z", DynValue.NewNumber(z));
t.Set("W", DynValue.NewNumber(w));
}
t.MetaTable = Meta(s, dim);
return DynValue.NewTable(t);
}
/// <summary>The global table: new(...), __call(...), Zero, One.</summary>
private static DynValue Constructor(Script s, int dim)
{
string name = dim == 2 ? "Vector2" : "Vector4";
var g = new Table(s);
DynValue make(DynValue[] args)
{
double c(int i) => i < args.Length ? Component(args[i], name, i) : 0;
// Vector4.new(v) with one number fills every component, as System.Numerics does.
if (args.Length == 1 && args[0].Type == DataType.Number)
{
double v = args[0].Number;
return NewVec(s, dim, v, v, v, v);
}
return NewVec(s, dim, c(0), c(1), c(2), c(3));
}
g["new"] = DynValue.NewCallback((ctx, a) => make(LuaArgs.Of(a, g)));
var mt = new Table(s);
mt["__call"] = DynValue.NewCallback((ctx, a) => make(LuaArgs.Of(a, g))); // Vector2(x, y): a[0] is the table
mt["__index"] = DynValue.NewCallback((ctx, a) =>
{
string key = a.Count > 1 && a[1].Type == DataType.String ? a[1].String : "";
return key switch
{
"Zero" => NewVec(s, dim, 0, 0, 0, 0),
"One" => NewVec(s, dim, 1, 1, 1, 1),
_ => DynValue.Nil,
};
});
mt["__tostring"] = DynValue.NewCallback((ctx, a) => DynValue.NewString(name));
g.MetaTable = mt;
return DynValue.NewTable(g);
}
private static double Component(DynValue v, string type, int i)
{
if (v.IsNil()) return 0;
double? d = v.CastToNumber();
if (d == null) throw new ScriptRuntimeException($"{type}.new: component {i + 1} must be a number, got {v.Type.ToLuaTypeString()}");
return d.Value;
}
/// <summary>The script's shared metatable for vectors of <paramref name="dim"/> components (made once).</summary>
private static Table Meta(Script s, int dim)
{
string key = dim == 2 ? Vec2MetaKey : Vec4MetaKey;
DynValue cached = s.Registry.Get(key);
if (cached.Type == DataType.Table) return cached.Table;
string name = dim == 2 ? "Vector2" : "Vector4";
var mt = new Table(s);
// Lowercase aliases: v.x reads X; v.x = 1 writes X. Other keys behave as in a plain table.
mt["__index"] = DynValue.NewCallback((ctx, a) =>
{
string? up = Alias(a.Count > 1 ? a[1] : DynValue.Nil, dim);
return up != null && a[0].Type == DataType.Table ? a[0].Table.RawGet(up) ?? DynValue.Nil : DynValue.Nil;
});
mt["__newindex"] = DynValue.NewCallback((ctx, a) =>
{
if (a.Count < 2 || a[0].Type != DataType.Table) return DynValue.Nil;
DynValue k = a[1];
DynValue v = a.Count > 2 ? a[2] : DynValue.Nil;
string? up = Alias(k, dim);
if (up != null) a[0].Table.Set(up, v);
else a[0].Table.Set(k, v);
return DynValue.Nil;
});
mt["__add"] = DynValue.NewCallback((ctx, a) => Arith(s, dim, name, a, '+'));
mt["__sub"] = DynValue.NewCallback((ctx, a) => Arith(s, dim, name, a, '-'));
mt["__mul"] = DynValue.NewCallback((ctx, a) => Arith(s, dim, name, a, '*'));
mt["__div"] = DynValue.NewCallback((ctx, a) => Arith(s, dim, name, a, '/'));
mt["__unm"] = DynValue.NewCallback((ctx, a) =>
{
Span<double> v = stackalloc double[4];
if (!Read(a.Count > 0 ? a[0] : DynValue.Nil, dim, v))
throw new ScriptRuntimeException($"attempt to negate a bad {name}");
return NewVec(s, dim, -v[0], -v[1], -v[2], -v[3]);
});
mt["__eq"] = DynValue.NewCallback((ctx, a) =>
{
Span<double> l = stackalloc double[4];
Span<double> r = stackalloc double[4];
bool ok = a.Count > 1 && Read(a[0], dim, l) && Read(a[1], dim, r);
for (int i = 0; ok && i < dim; i++) ok = l[i] == r[i];
return DynValue.NewBoolean(ok);
});
mt["__tostring"] = DynValue.NewCallback((ctx, a) =>
{
Span<double> v = stackalloc double[4];
if (!Read(a.Count > 0 ? a[0] : DynValue.Nil, dim, v)) return DynValue.NewString(name + "(?)");
return DynValue.NewString(dim == 2
? $"{name}({Fmt(v[0])}, {Fmt(v[1])})"
: $"{name}({Fmt(v[0])}, {Fmt(v[1])}, {Fmt(v[2])}, {Fmt(v[3])})");
});
s.Registry.Set(key, DynValue.NewTable(mt));
return mt;
}
private static string? Alias(DynValue key, int dim)
{
if (key.Type != DataType.String || key.String.Length != 1) return null;
int i = key.String[0] switch { 'x' => 0, 'y' => 1, 'z' => 2, 'w' => 3, _ => -1 };
return i >= 0 && i < dim ? Upper[i] : null;
}
private static string Fmt(double d) => d.ToString("0.######", CultureInfo.InvariantCulture);
/// <summary>a op b: vector with vector (component-wise) or with a number (every component).</summary>
private static DynValue Arith(Script s, int dim, string name, CallbackArguments a, char op)
{
DynValue left = a.Count > 0 ? a[0] : DynValue.Nil;
DynValue right = a.Count > 1 ? a[1] : DynValue.Nil;
Span<double> l = stackalloc double[4];
Span<double> r = stackalloc double[4];
if (!Operand(left, dim, l) || !Operand(right, dim, r))
{
string verb = op switch { '+' => "add", '-' => "subtract", '*' => "multiply", _ => "divide" };
throw new ScriptRuntimeException(
$"attempt to {verb} a {TypeName(left, dim, name)} and a {TypeName(right, dim, name)}");
}
Span<double> o = stackalloc double[4];
for (int i = 0; i < 4; i++)
o[i] = op switch { '+' => l[i] + r[i], '-' => l[i] - r[i], '*' => l[i] * r[i], _ => l[i] / r[i] };
return NewVec(s, dim, o[0], o[1], o[2], o[3]);
}
/// <summary>A number fills every component; a vector (or vector-shaped table) gives its own.</summary>
private static bool Operand(DynValue v, int dim, Span<double> into)
{
if (v.Type == DataType.Number)
{
into.Fill(v.Number);
return true;
}
return Read(v, dim, into);
}
private static string TypeName(DynValue v, int dim, string name) =>
v.Type == DataType.Table && Read(v, dim, stackalloc double[4]) ? name : v.Type.ToLuaTypeString();
/// <summary>
/// The first <paramref name="dim"/> components of a vector-shaped table: X/Y/Z/W, x/y/z/w,
/// or [1]..[4]. Missing components are false (the rest of <paramref name="into"/> is 0).
/// </summary>
private static bool Read(DynValue v, int dim, Span<double> into)
{
into.Clear();
if (v.Type != DataType.Table) return false;
Table t = v.Table;
for (int i = 0; i < dim; i++)
{
DynValue c = t.RawGet(Upper[i]) ?? DynValue.Nil;
if (c.IsNil()) c = t.RawGet(Upper[i].ToLowerInvariant()) ?? DynValue.Nil;
if (c.IsNil()) c = t.RawGet(i + 1) ?? DynValue.Nil;
double? d = c.Type == DataType.Number ? c.Number : c.Type == DataType.String ? c.CastToNumber() : null;
if (d == null) return false;
into[i] = d.Value;
}
return true;
}
// ── Helpers for the imgui functions ─────────────────────────────────
/// <summary>A Vector2, {x, y}, {X=, Y=} or {x=, y=}. False for nil or anything else.</summary>
public static bool TryVec2(DynValue v, out float x, out float y)
{
Span<double> c = stackalloc double[4];
bool ok = Read(v, 2, c);
x = ok ? (float)c[0] : 0f;
y = ok ? (float)c[1] : 0f;
return ok;
}
/// <summary>A Vector4, {x, y, z, w}, {X=, ...} or {x=, ...}. False for nil or anything else.</summary>
public static bool TryVec4(DynValue v, out float x, out float y, out float z, out float w)
{
Span<double> c = stackalloc double[4];
bool ok = Read(v, 4, c);
x = ok ? (float)c[0] : 0f;
y = ok ? (float)c[1] : 0f;
z = ok ? (float)c[2] : 0f;
w = ok ? (float)c[3] : 0f;
return ok;
}
/// <summary>
/// A colour: a number is taken as 0xAABBGGRR as is; a Vector4 (or {r, g, b, a} table) with
/// 0..1 components becomes 0xAABBGGRR (R in the low byte), clamped, rounded as ImGui does.
/// </summary>
public static uint ColorU32(DynValue v)
{
if (v.Type == DataType.Number)
{
double d = v.Number;
if (!double.IsFinite(d)) return 0;
return d >= 0 ? (uint)Math.Min(d, uint.MaxValue) : unchecked((uint)(int)Math.Max(d, int.MinValue));
}
if (TryVec4(v, out float r, out float g, out float b, out float a))
return Byte(r) | (Byte(g) << 8) | (Byte(b) << 16) | (Byte(a) << 24);
throw new ScriptRuntimeException($"a colour is a Vector4 (0..1) or a 0xAABBGGRR number, not {v.Type.ToLuaTypeString()}");
}
/// <summary>ImGui's IM_F32_TO_INT8_SAT: saturate, * 255, + 0.5.</summary>
private static uint Byte(float f)
{
if (!(f > 0f)) return 0; // NaN too
if (f >= 1f) return 255;
return (uint)(f * 255f + 0.5f);
}
// ── ImGui enums (ImGui.NET 1.91.6.1) ────────────────────────────────
private static readonly (string, int)[] WindowFlags =
{
("None", 0), ("NoTitleBar", 1), ("NoResize", 2), ("NoMove", 4), ("NoScrollbar", 8),
("NoScrollWithMouse", 16), ("NoCollapse", 32), ("NoDecoration", 43), ("AlwaysAutoResize", 64),
("NoBackground", 128), ("NoSavedSettings", 256), ("NoMouseInputs", 512), ("MenuBar", 1024),
("HorizontalScrollbar", 2048), ("NoFocusOnAppearing", 4096), ("NoBringToFrontOnFocus", 8192),
("AlwaysVerticalScrollbar", 16384), ("AlwaysHorizontalScrollbar", 32768), ("NoNavInputs", 65536),
("NoNavFocus", 131072), ("NoNav", 196608), ("NoInputs", 197120), ("UnsavedDocument", 262144),
("NoDocking", 524288),
};
private static readonly (string, int)[] Cond =
{
("None", 0), ("Always", 1), ("Once", 2), ("FirstUseEver", 4), ("Appearing", 8),
};
private static readonly (string, int)[] Col =
{
("Text", 0), ("TextDisabled", 1), ("WindowBg", 2), ("ChildBg", 3), ("PopupBg", 4), ("Border", 5),
("BorderShadow", 6), ("FrameBg", 7), ("FrameBgHovered", 8), ("FrameBgActive", 9), ("TitleBg", 10),
("TitleBgActive", 11), ("TitleBgCollapsed", 12), ("MenuBarBg", 13), ("ScrollbarBg", 14),
("ScrollbarGrab", 15), ("ScrollbarGrabHovered", 16), ("ScrollbarGrabActive", 17), ("CheckMark", 18),
("SliderGrab", 19), ("SliderGrabActive", 20), ("Button", 21), ("ButtonHovered", 22), ("ButtonActive", 23),
("Header", 24), ("HeaderHovered", 25), ("HeaderActive", 26), ("Separator", 27), ("SeparatorHovered", 28),
("SeparatorActive", 29), ("ResizeGrip", 30), ("ResizeGripHovered", 31), ("ResizeGripActive", 32),
("TabHovered", 33), ("Tab", 34), ("TabSelected", 35), ("TabSelectedOverline", 36), ("TabDimmed", 37),
("TabDimmedSelected", 38), ("TabDimmedSelectedOverline", 39), ("DockingPreview", 40),
("DockingEmptyBg", 41), ("PlotLines", 42), ("PlotLinesHovered", 43), ("PlotHistogram", 44),
("PlotHistogramHovered", 45), ("TableHeaderBg", 46), ("TableBorderStrong", 47), ("TableBorderLight", 48),
("TableRowBg", 49), ("TableRowBgAlt", 50), ("TextLink", 51), ("TextSelectedBg", 52),
("DragDropTarget", 53), ("NavCursor", 54), ("NavWindowingHighlight", 55), ("NavWindowingDimBg", 56),
("ModalWindowDimBg", 57), ("COUNT", 58),
};
private static readonly (string, int)[] TreeNodeFlags =
{
("None", 0), ("Selected", 1), ("Framed", 2), ("AllowOverlap", 4), ("NoTreePushOnOpen", 8),
("NoAutoOpenOnLog", 16), ("CollapsingHeader", 26), ("DefaultOpen", 32), ("OpenOnDoubleClick", 64),
("OpenOnArrow", 128), ("Leaf", 256), ("Bullet", 512), ("FramePadding", 1024), ("SpanAvailWidth", 2048),
("SpanFullWidth", 4096), ("SpanTextWidth", 8192), ("SpanAllColumns", 16384),
("NavLeftJumpsBackHere", 32768),
};
private static readonly (string, int)[] InputTextFlags =
{
("None", 0), ("CharsDecimal", 1), ("CharsHexadecimal", 2), ("CharsScientific", 4), ("CharsUppercase", 8),
("CharsNoBlank", 16), ("AllowTabInput", 32), ("EnterReturnsTrue", 64), ("EscapeClearsAll", 128),
("CtrlEnterForNewLine", 256), ("ReadOnly", 512), ("Password", 1024), ("AlwaysOverwrite", 2048),
("AutoSelectAll", 4096), ("ParseEmptyRefVal", 8192), ("DisplayEmptyRefVal", 16384),
("NoHorizontalScroll", 32768), ("NoUndoRedo", 65536), ("ElideLeft", 131072),
};
private static readonly (string, int)[] SelectableFlags =
{
("None", 0), ("NoAutoClosePopups", 1), ("SpanAllColumns", 2), ("AllowDoubleClick", 4), ("Disabled", 8),
("AllowOverlap", 16), ("Highlight", 32),
};
private static readonly (string, int)[] SliderFlags =
{
("None", 0), ("Logarithmic", 32), ("NoRoundToFormat", 64), ("NoInput", 128), ("WrapAround", 256),
("ClampOnInput", 512), ("ClampZeroRange", 1024), ("AlwaysClamp", 1536),
};
private static readonly (string, int)[] ChildFlags =
{
("None", 0), ("Borders", 1), ("AlwaysUseWindowPadding", 2), ("ResizeX", 4), ("ResizeY", 8),
("AutoResizeX", 16), ("AutoResizeY", 32), ("AlwaysAutoResize", 64), ("FrameStyle", 128),
("NavFlattened", 256),
};
}

View file

@ -0,0 +1,332 @@
using System;
using System.Buffers;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using System.Text.Encodings.Web;
using System.Text.Json;
using MoonSharp.Interpreter;
namespace RynthCore.Plugin.RynthLua;
/// <summary>
/// <c>require("json")</c>: <c>json.encode(value [, pretty])</c> and <c>json.decode(text)</c>
/// (also <c>Encode</c>/<c>Decode</c>). Written by hand with Utf8JsonWriter / JsonDocument, no
/// reflection serialization (NativeAOT).
///
/// Lua → JSON: nil → null; a table whose keys are exactly 1..n → array (an empty table → [])
/// ; any other table → object (string keys, number keys written as text); a WorldObject →
/// its Id. Functions, coroutines, userdata, NaN/inf and tables that contain themselves are
/// errors that say where the bad value is.
/// JSON → Lua: objects and arrays → tables (arrays 1-based), null → nil (an array keeps its
/// other indexes), numbers → numbers.
///
/// Also the names of the JSON module UtilityBelt's interpreter ships (MoonSharp/WattleScript):
/// <c>json.parse(text)</c> (like decode, but JSON null becomes <c>json.null()</c>, so arrays
/// keep their holes), <c>json.serialize(value)</c> (encode), <c>json.null()</c> (the null
/// value, which encodes as null) and <c>json.isnull(v)</c> (true for nil and json.null()).
/// Typed enum values encode as their number.
/// </summary>
internal static class LibraryJson
{
/// <summary>Nesting limit both ways (a runaway structure errors instead of overflowing the stack).</summary>
public const int MaxDepth = 200;
private static readonly JsonWriterOptions CompactOptions = new()
{
Indented = false,
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
MaxDepth = MaxDepth + 8,
};
private static readonly JsonWriterOptions PrettyOptions = new()
{
Indented = true,
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
MaxDepth = MaxDepth + 8,
};
private static readonly JsonDocumentOptions ReadOptions = new()
{
AllowTrailingCommas = true,
CommentHandling = JsonCommentHandling.Skip,
MaxDepth = MaxDepth,
};
public static DynValue CreateModule(Script s)
{
var m = new Table(s);
DynValue encode = DynValue.NewCallback((c, a) =>
{
var args = LuaArgs.Of(a, m);
return DynValue.NewString(Encode(LuaArgs.At(args, 0), LuaArgs.At(args, 1).CastToBool(), "json.encode"));
});
DynValue decode = DynValue.NewCallback((c, a) =>
{
DynValue text = LuaArgs.At(LuaArgs.Of(a, m), 0);
if (text.Type != DataType.String)
throw new ScriptRuntimeException($"json.decode(text) needs a string, got {TypeName(text)}");
return Decode(s, text.String, "json.decode");
});
m.Set("encode", encode);
m.Set("decode", decode);
m.Set("Encode", encode);
m.Set("Decode", decode);
DynValue jsonNull = NullValue(s);
m.Set("serialize", encode);
m.Set("parse", DynValue.NewCallback((c, a) =>
{
DynValue text = LuaArgs.At(LuaArgs.Of(a, m), 0);
if (text.Type != DataType.String)
throw new ScriptRuntimeException($"json.parse(text) needs a string, got {TypeName(text)}");
return Decode(s, text.String, "json.parse", jsonNull);
}));
m.Set("null", DynValue.NewCallback((c, a) => jsonNull));
m.Set("isnull", DynValue.NewCallback((c, a) =>
{
DynValue v = LuaArgs.At(LuaArgs.Of(a, m), 0);
return DynValue.NewBoolean(v.IsNil() || IsNull(v));
}));
var mt = new Table(s);
mt.Set("__tostring", DynValue.NewCallback((c, a) => DynValue.NewString("module json")));
m.MetaTable = mt;
return DynValue.NewTable(m);
}
private const string NullMarker = "__rynth_jsonnull";
/// <summary>This script's json.null() value: a table that encodes as null and prints as "null".</summary>
private static DynValue NullValue(Script s)
{
DynValue cached = s.Registry.Get("rynth.jsonnull");
if (cached.Type == DataType.Table) return cached;
var t = new Table(s);
t.Set(NullMarker, DynValue.True);
var mt = new Table(s);
mt.Set("__tostring", DynValue.NewCallback((c, a) => DynValue.NewString("null")));
t.MetaTable = mt;
DynValue v = DynValue.NewTable(t);
s.Registry.Set("rynth.jsonnull", v);
return v;
}
private static bool IsNull(DynValue v) =>
v.Type == DataType.Table && v.Table.RawGet(NullMarker) is { Type: DataType.Boolean, Boolean: true };
// ── Encode ──────────────────────────────────────────────────────────────
/// <summary>JSON text for <paramref name="value"/>; <paramref name="what"/> prefixes error messages.</summary>
public static string Encode(DynValue value, bool pretty, string what)
{
var buffer = new ArrayBufferWriter<byte>();
try
{
using (var w = new Utf8JsonWriter(buffer, pretty ? PrettyOptions : CompactOptions))
{
var onPath = new HashSet<Table>(ReferenceEqualityComparer.Instance);
Write(w, value, onPath, new List<string>(), what);
}
}
catch (ScriptRuntimeException) { throw; }
catch (Exception ex) when (ex is ArgumentException or InvalidOperationException)
{
throw new ScriptRuntimeException($"{what}: {ex.Message}");
}
return Encoding.UTF8.GetString(buffer.WrittenSpan);
}
private static void Write(Utf8JsonWriter w, DynValue v, HashSet<Table> onPath, List<string> path, string what)
{
switch (v.Type)
{
case DataType.Nil:
case DataType.Void:
w.WriteNullValue();
return;
case DataType.Boolean:
w.WriteBooleanValue(v.Boolean);
return;
case DataType.Number:
WriteNumber(w, v.Number, path, what);
return;
case DataType.String:
w.WriteStringValue(v.String);
return;
case DataType.Tuple:
Write(w, v.Tuple.Length > 0 ? v.Tuple[0] : DynValue.Nil, onPath, path, what);
return;
case DataType.Table:
WriteTable(w, v.Table, onPath, path, what);
return;
default:
throw Fail(what, path, $"can't encode a {TypeName(v)}");
}
}
private static void WriteNumber(Utf8JsonWriter w, double d, List<string> path, string what)
{
if (double.IsNaN(d) || double.IsInfinity(d))
throw Fail(what, path, $"can't encode {(double.IsNaN(d) ? "nan" : "an infinite number")} (JSON has no such number)");
// Whole numbers as integers ("12", not "12.0"), within the exactly representable range.
if (Math.Floor(d) == d && Math.Abs(d) <= 9007199254740992.0) w.WriteNumberValue((long)d);
else w.WriteNumberValue(d);
}
private static void WriteTable(Utf8JsonWriter w, Table t, HashSet<Table> onPath, List<string> path, string what)
{
DynValue self = DynValue.NewTable(t);
if (IsNull(self)) { w.WriteNullValue(); return; }
if (LuaEnumValues.TryRead(self, out _, out long enumValue)) { w.WriteNumberValue(enumValue); return; }
// A WorldObject (RynthLuaPlugin.WrapObject) is written as its id: its other raw
// fields are action methods, and ids are what a script can look it up by again.
DynValue? marker = t.RawGet("__rynth_object");
if (marker != null && marker.Type == DataType.Boolean && marker.Boolean)
{
DynValue? id = t.RawGet("Id");
if (id != null && id.Type == DataType.Number) { w.WriteNumberValue((long)id.Number); return; }
}
if (path.Count >= MaxDepth) throw Fail(what, path, $"tables nested more than {MaxDepth} deep");
if (!onPath.Add(t)) throw Fail(what, path, "the table contains itself (a cycle can't be written as JSON)");
// An array when the keys are exactly 1..n (every key a positive whole number, the
// largest equal to the count).
int count = 0;
double max = 0;
bool isArray = true;
foreach (TablePair p in t.Pairs)
{
if (p.Value.IsNil()) continue;
count++;
if (!isArray) continue;
DynValue k = p.Key;
if (k.Type == DataType.Number && k.Number >= 1 && Math.Floor(k.Number) == k.Number)
{
if (k.Number > max) max = k.Number;
}
else isArray = false;
}
if (isArray && max == count)
{
w.WriteStartArray();
for (int i = 1; i <= count; i++)
{
path.Add("[" + i.ToString(CultureInfo.InvariantCulture) + "]");
Write(w, t.RawGet(i) ?? DynValue.Nil, onPath, path, what);
path.RemoveAt(path.Count - 1);
}
w.WriteEndArray();
}
else
{
w.WriteStartObject();
foreach (TablePair p in t.Pairs)
{
if (p.Value.IsNil()) continue;
string key = p.Key.Type switch
{
DataType.String => p.Key.String,
DataType.Number => FormatKey(p.Key.Number),
_ => throw Fail(what, path, $"can't encode a table key that is a {TypeName(p.Key)} (JSON keys are text)"),
};
w.WritePropertyName(key);
path.Add(p.Key.Type == DataType.String ? "." + key : "[" + key + "]");
Write(w, p.Value, onPath, path, what);
path.RemoveAt(path.Count - 1);
}
w.WriteEndObject();
}
onPath.Remove(t);
}
private static string FormatKey(double d) =>
Math.Floor(d) == d && Math.Abs(d) <= 9007199254740992.0
? ((long)d).ToString(CultureInfo.InvariantCulture)
: d.ToString("R", CultureInfo.InvariantCulture);
private static ScriptRuntimeException Fail(string what, List<string> path, string message)
{
// Deep paths show their last few steps only.
const int Shown = 8;
string at = path.Count <= Shown
? string.Concat(path).TrimStart('.')
: "..." + string.Concat(path.GetRange(path.Count - Shown, Shown));
string where = path.Count == 0 ? string.Empty : " (at " + at + ")";
return new ScriptRuntimeException($"{what}: {message}{where}");
}
internal static string TypeName(DynValue v) => v.Type switch
{
DataType.Nil or DataType.Void => "nil",
DataType.Boolean => "boolean",
DataType.Number => "number",
DataType.String => "string",
DataType.Table => "table",
DataType.Function or DataType.ClrFunction => "function",
DataType.Thread => "coroutine",
DataType.UserData => "userdata",
_ => v.Type.ToString().ToLowerInvariant(),
};
// ── Decode ──────────────────────────────────────────────────────────────
/// <summary>The Lua value for JSON <paramref name="text"/>; <paramref name="what"/> prefixes error messages.</summary>
public static DynValue Decode(Script s, string text, string what, DynValue? jsonNull = null)
{
try
{
using JsonDocument doc = JsonDocument.Parse(text, ReadOptions);
return ToLua(s, doc.RootElement, jsonNull);
}
catch (JsonException ex)
{
throw new ScriptRuntimeException($"{what}: not valid JSON: {ex.Message}");
}
}
/// <param name="jsonNull">What JSON null becomes (nil when not given).</param>
internal static DynValue ToLua(Script s, JsonElement e, DynValue? jsonNull = null)
{
switch (e.ValueKind)
{
case JsonValueKind.Object:
{
var t = new Table(s);
foreach (JsonProperty p in e.EnumerateObject())
{
DynValue v = ToLua(s, p.Value, jsonNull);
if (!v.IsNil()) t.Set(p.Name, v);
}
return DynValue.NewTable(t);
}
case JsonValueKind.Array:
{
var t = new Table(s);
int i = 0;
foreach (JsonElement item in e.EnumerateArray())
{
i++;
DynValue v = ToLua(s, item, jsonNull);
if (!v.IsNil()) t.Set(i, v);
}
return DynValue.NewTable(t);
}
case JsonValueKind.String:
return DynValue.NewString(e.GetString() ?? string.Empty);
case JsonValueKind.Number:
if (e.TryGetDouble(out double d)) return DynValue.NewNumber(d);
return DynValue.NewNumber(double.Parse(e.GetRawText(), NumberStyles.Float, CultureInfo.InvariantCulture));
case JsonValueKind.True:
return DynValue.True;
case JsonValueKind.False:
return DynValue.False;
case JsonValueKind.Null:
return jsonNull ?? DynValue.Nil;
default:
return DynValue.Nil;
}
}
}

View file

@ -0,0 +1,187 @@
using System;
using System.Globalization;
using MoonSharp.Interpreter;
namespace RynthCore.Plugin.RynthLua;
/// <summary>
/// <c>require("rynth.ai")</c>: RynthAi through its "RynthAi.Script" interface (RynthAiBridge).
///
/// ai.Available (also IsLoaded) true while RynthAi's interface is there
/// ai.Evaluate(expr) a meta expression; numbers come back as numbers
/// ai.GetSetting(name) number / boolean / text, nil for an unknown setting
/// ai.SetSetting(name, value) true, or false for an unknown setting (saves the profile)
/// ai.SettingNames() every setting name (sorted)
/// ai.MacroRunning read, or assign true/false to start/stop the macro
/// ai.GoTo(ns, ew) walk there (numbers, or "33.5N" / "44.8W")
/// ai.Stop() stop navigation (and the macro)
/// ai.FindNearest(name [, portalsOnly]) WorldObject, distance (nil when nothing matches)
/// ai.DistanceTo(objectOrId) metres, -1 when unknown
/// ai.IsPathClear(objectOrIdOrName) line of sight
/// ai.Command(text) (SubmitCommand) a chat line as if typed (/ra, /vt, ...; AC's parser without RynthAi)
///
/// Everything except Available and Command raises "RynthAi isn't loaded ..." when RynthAi
/// isn't there, so a script can check <c>ai.Available</c> first or pcall.
/// </summary>
public sealed partial class RynthLuaPlugin
{
private DynValue CreateRynthAiModule(Script s, ScriptContext ctx)
{
var m = new Table(s);
void Need(string what)
{
if (!_ai.Available) throw new ScriptRuntimeException($"rynth.ai.{what}: {RynthAiBridge.NotLoaded}");
}
string Text(DynValue[] args, int i, string what)
{
DynValue v = LuaArgs.At(args, i);
string t = v.Type is DataType.String or DataType.Number ? v.CastToString() ?? string.Empty : string.Empty;
if (t.Trim().Length == 0) throw new ScriptRuntimeException($"rynth.ai.{what} needs text");
return t;
}
uint Target(DynValue v, string what)
{
uint id = LuaArgs.Id(v);
if (id == 0 && v.Type == DataType.String && _ai.FindNearest(v.String, portalOrNpcOnly: false, out uint found, out _))
id = found;
if (id == 0) throw new ScriptRuntimeException($"rynth.ai.{what}: no object by that id, object or name");
return id;
}
m.Set("Evaluate", DynValue.NewCallback((c, a) =>
{
string expression = Text(LuaArgs.Of(a, m), 0, "Evaluate(expression)");
Need("Evaluate");
return EvalExpression(expression);
}));
m.Set("GetSetting", DynValue.NewCallback((c, a) =>
{
string name = Text(LuaArgs.Of(a, m), 0, "GetSetting(name)");
Need("GetSetting");
string? v = _ai.GetSetting(name);
if (v == null) return DynValue.Nil;
if (double.TryParse(v, NumberStyles.Float, CultureInfo.InvariantCulture, out double d)) return DynValue.NewNumber(d);
if (v.Equals("true", StringComparison.OrdinalIgnoreCase)) return DynValue.True;
if (v.Equals("false", StringComparison.OrdinalIgnoreCase)) return DynValue.False;
return DynValue.NewString(v);
}));
m.Set("SetSetting", DynValue.NewCallback((c, a) =>
{
var args = LuaArgs.Of(a, m);
string name = Text(args, 0, "SetSetting(name, value)");
DynValue v = LuaArgs.At(args, 1);
string text = v.Type switch
{
DataType.Boolean => v.Boolean ? "1" : "0",
DataType.Number => v.Number.ToString("R", CultureInfo.InvariantCulture),
DataType.String => v.String,
_ => throw new ScriptRuntimeException($"rynth.ai.SetSetting(\"{name}\", value): the value must be a number, text or boolean"),
};
Need("SetSetting");
return DynValue.NewBoolean(_ai.SetSetting(name, text));
}));
m.Set("SettingNames", DynValue.NewCallback((c, a) =>
{
Need("SettingNames");
var list = new Table(s);
foreach (string n in _ai.SettingNames()) list.Append(DynValue.NewString(n));
return DynValue.NewTable(list);
}));
m.Set("GoTo", DynValue.NewCallback((c, a) =>
{
var args = LuaArgs.Of(a, m);
double ns = ParseCoord(LuaArgs.At(args, 0), 'N', 'S');
double ew = ParseCoord(LuaArgs.At(args, 1), 'E', 'W');
Need("GoTo");
return DynValue.NewBoolean(_ai.GoTo(ns, ew));
}));
m.Set("Stop", DynValue.NewCallback((c, a) =>
{
Need("Stop");
_ai.Stop();
return DynValue.Nil;
}));
m.Set("FindNearest", DynValue.NewCallback((c, a) =>
{
var args = LuaArgs.Of(a, m);
string name = Text(args, 0, "FindNearest(name [, portalsOnly])");
bool portalsOnly = LuaArgs.At(args, 1).CastToBool();
Need("FindNearest");
if (!_ai.FindNearest(name, portalsOnly, out uint id, out double distance) || id == 0) return DynValue.Nil;
return DynValue.NewTuple(WrapObject(s, ctx, id), DynValue.NewNumber(distance));
}));
m.Set("DistanceTo", DynValue.NewCallback((c, a) =>
{
DynValue target = LuaArgs.At(LuaArgs.Of(a, m), 0);
Need("DistanceTo");
return DynValue.NewNumber(_ai.DistanceTo(Target(target, "DistanceTo(objectOrId)")));
}));
m.Set("IsPathClear", DynValue.NewCallback((c, a) =>
{
DynValue target = LuaArgs.At(LuaArgs.Of(a, m), 0);
Need("IsPathClear");
return DynValue.NewBoolean(_ai.IsPathClear(Target(target, "IsPathClear(objectOrIdOrName)")));
}));
DynValue command = DynValue.NewCallback((c, a) =>
{
string text = LuaArgs.Str(LuaArgs.At(LuaArgs.Of(a, m), 0)).Trim();
if (text.Length == 0) throw new ScriptRuntimeException("rynth.ai.Command(text) needs a command");
_ai.SubmitCommand(text);
return DynValue.Nil;
});
m.Set("Command", command);
m.Set("SubmitCommand", command);
// Live fields: Available / IsLoaded, MacroRunning (read and write).
var mt = new Table(s);
mt.Set("__index", DynValue.NewCallback((c, a) =>
{
string key = a.Count > 1 && a[1].Type == DataType.String ? a[1].String : string.Empty;
switch (key)
{
case "Available":
case "IsLoaded":
return DynValue.NewBoolean(_ai.Available);
case "MacroRunning":
return DynValue.NewBoolean(_ai.MacroRunning);
default:
return DynValue.Nil;
}
}));
mt.Set("__newindex", DynValue.NewCallback((c, a) =>
{
string key = a.Count > 1 && a[1].Type == DataType.String ? a[1].String : string.Empty;
DynValue v = a.Count > 2 ? a[2] : DynValue.Nil;
switch (key)
{
case "MacroRunning":
Need("MacroRunning");
_ai.MacroRunning = v.CastToBool();
return DynValue.Nil;
case "Available":
case "IsLoaded":
throw new ScriptRuntimeException($"rynth.ai.{key} is read-only");
default:
// Script's own fields on the module are fine.
m.Set(a[1], v);
return DynValue.Nil;
}
}));
mt.Set("__tostring", DynValue.NewCallback((c, a) =>
DynValue.NewString(_ai.Available ? "module rynth.ai (RynthAi loaded)" : "module rynth.ai (RynthAi not loaded)")));
m.MetaTable = mt;
return DynValue.NewTable(m);
}
}

View file

@ -0,0 +1,381 @@
using System;
using System.Buffers;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.Encodings.Web;
using System.Text.Json;
using System.Threading;
using MoonSharp.Interpreter;
namespace RynthCore.Plugin.RynthLua;
/// <summary>
/// <c>require("storage")</c>: a script's saved values, as JSON in its data folder
/// (<c>C:\Games\RynthSuite\RynthLua\Data\&lt;Script&gt;\</c>):
///
/// storage.Get(key [, default]) the value, or default (nil) when there is none
/// storage.Set(key, value) any JSON-able value (tables, numbers, text, booleans); nil removes
/// storage.Remove(key) true when it was there
/// storage.Has(key), storage.Keys() (sorted), storage.Clear(), storage.Save() (write now)
/// storage.Character the same, for the logged-in character (one file per character)
///
/// Values are copies: Set encodes the value right away (so a table changed afterwards isn't
/// changed in storage until it is Set again) and Get returns a fresh table each time.
/// Keys are just names inside one JSON file, never paths. Writes are debounced (at most
/// ~2 s after the first change) on a timer thread, atomic (temp file, then a move over the
/// old one), and flushed when the script stops.
/// </summary>
internal static class LibraryStorage
{
public const string FileName = "storage.json";
public const string CharacterFolder = "characters";
/// <param name="dataRoot">RynthLua's data folder (the script's folder is made under it).</param>
/// <param name="characterKey">"server|character" of the logged-in character, "" before login.</param>
public static DynValue CreateModule(Script s, ScriptContext ctx, string dataRoot, Func<string> characterKey)
{
string folder = LibraryPaths.ScriptDataFolder(dataRoot, ctx.Name);
Action<string> warn = msg => ctx.Host.Print("storage: " + msg);
var main = new LibraryStore(Path.Combine(folder, FileName), warn);
var perCharacter = new Dictionary<string, LibraryStore>(StringComparer.OrdinalIgnoreCase);
ctx.OnStop.Add(() =>
{
main.Dispose();
foreach (LibraryStore st in perCharacter.Values) st.Dispose();
});
LibraryStore CharacterStore()
{
string key = characterKey();
if (key.Length == 0)
throw new ScriptRuntimeException("storage.Character needs a logged-in character");
if (!perCharacter.TryGetValue(key, out LibraryStore? st))
{
string file = Path.Combine(folder, CharacterFolder, LibraryPaths.SafeFileName(key.Replace('|', '_')) + ".json");
perCharacter[key] = st = new LibraryStore(file, warn);
}
return st;
}
Table storage = CreateApi(s, () => main, "storage");
Table character = CreateApi(s, CharacterStore, "storage.Character");
storage.Set("Character", DynValue.NewTable(character));
return DynValue.NewTable(storage);
}
private static Table CreateApi(Script s, Func<LibraryStore> store, string what)
{
var t = new Table(s);
string Key(DynValue[] args, string method)
{
DynValue k = LuaArgs.At(args, 0);
if (k.Type != DataType.String && k.Type != DataType.Number)
throw new ScriptRuntimeException($"{what}.{method}(key, ...) needs a key (text), got {LibraryJson.TypeName(k)}");
string key = k.CastToString() ?? string.Empty;
if (key.Length == 0) throw new ScriptRuntimeException($"{what}.{method}: the key can't be empty");
if (key.Length > 512) throw new ScriptRuntimeException($"{what}.{method}: keys are at most 512 characters");
return key;
}
t.Set("Get", DynValue.NewCallback((c, a) =>
{
var args = LuaArgs.Of(a, t);
string key = Key(args, "Get");
string? json = store().Get(key);
if (json == null) return LuaArgs.At(args, 1);
DynValue v = LibraryJson.Decode(s, json, $"{what}.Get(\"{key}\")");
return v.IsNil() ? LuaArgs.At(args, 1) : v;
}));
t.Set("Set", DynValue.NewCallback((c, a) =>
{
var args = LuaArgs.Of(a, t);
string key = Key(args, "Set");
DynValue value = LuaArgs.At(args, 1);
if (value.IsNil()) store().Remove(key);
else store().Set(key, LibraryJson.Encode(value, false, $"{what}.Set(\"{key}\")"));
return DynValue.Nil;
}));
t.Set("Remove", DynValue.NewCallback((c, a) =>
DynValue.NewBoolean(store().Remove(Key(LuaArgs.Of(a, t), "Remove")))));
t.Set("Has", DynValue.NewCallback((c, a) =>
DynValue.NewBoolean(store().Get(Key(LuaArgs.Of(a, t), "Has")) != null)));
t.Set("Keys", DynValue.NewCallback((c, a) =>
{
var list = new Table(s);
foreach (string k in store().Keys()) list.Append(DynValue.NewString(k));
return DynValue.NewTable(list);
}));
t.Set("Clear", DynValue.NewCallback((c, a) => { store().Clear(); return DynValue.Nil; }));
t.Set("Save", DynValue.NewCallback((c, a) => DynValue.NewBoolean(store().Flush())));
var mt = new Table(s);
mt.Set("__tostring", DynValue.NewCallback((c, a) => DynValue.NewString(what)));
t.MetaTable = mt;
return t;
}
}
/// <summary>
/// One JSON file of key → value. Values are kept as their JSON text (so a stored value is a
/// copy). Thread-safe: the debounce timer writes from a pool thread.
/// </summary>
internal sealed class LibraryStore : IDisposable
{
public const int DebounceMs = 2000;
/// <summary>One file operation at a time across every store (a restarted script's new store
/// never reads while its old one is still writing).</summary>
private static readonly object IoLock = new();
private static readonly JsonWriterOptions FileWriterOptions = new()
{
Indented = true,
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
};
private readonly string _path;
private readonly Action<string> _warn;
private readonly object _lock = new();
private Dictionary<string, string>? _values;
private long _version; // bumped on every change
private long _savedVersion; // the version on disk
private Timer? _timer;
private bool _disposed;
public LibraryStore(string path, Action<string> warn)
{
_path = path;
_warn = warn;
}
public string FilePath => _path;
private Dictionary<string, string> Values
{
get
{
if (_values != null) return _values;
_values = new Dictionary<string, string>(StringComparer.Ordinal);
lock (IoLock)
{
try
{
if (!File.Exists(_path)) return _values;
using JsonDocument doc = JsonDocument.Parse(File.ReadAllBytes(_path),
new JsonDocumentOptions { AllowTrailingCommas = true, CommentHandling = JsonCommentHandling.Skip, MaxDepth = LibraryJson.MaxDepth });
if (doc.RootElement.ValueKind != JsonValueKind.Object)
throw new JsonException("the file isn't a JSON object");
foreach (JsonProperty p in doc.RootElement.EnumerateObject())
_values[p.Name] = p.Value.GetRawText();
}
catch (Exception ex) when (ex is JsonException or IOException or UnauthorizedAccessException)
{
// Keep the unreadable file for the player instead of overwriting it.
string aside = _path + ".unreadable";
try { File.Copy(_path, aside, overwrite: true); } catch { }
_warn($"couldn't read {Path.GetFileName(_path)} ({ex.Message}); starting empty, the old file is kept as {Path.GetFileName(aside)}");
_values.Clear();
}
}
return _values;
}
}
public string? Get(string key)
{
lock (_lock) return Values.TryGetValue(key, out string? json) ? json : null;
}
public void Set(string key, string json)
{
lock (_lock)
{
if (Values.TryGetValue(key, out string? old) && old == json) return;
Values[key] = json;
Changed();
}
}
public bool Remove(string key)
{
lock (_lock)
{
if (!Values.Remove(key)) return false;
Changed();
return true;
}
}
public string[] Keys()
{
lock (_lock)
{
var keys = Values.Keys.ToArray();
Array.Sort(keys, StringComparer.OrdinalIgnoreCase);
return keys;
}
}
public void Clear()
{
lock (_lock)
{
if (Values.Count == 0) return;
Values.Clear();
Changed();
}
}
/// <summary>Under _lock: note the change and start the debounce clock if it isn't running.</summary>
private void Changed()
{
_version++;
if (_disposed) return;
if (_timer == null) _timer = new Timer(state => Flush(),null, DebounceMs, Timeout.Infinite);
else if (_version == _savedVersion + 1) _timer.Change(DebounceMs, Timeout.Infinite);
}
/// <summary>Writes the file if anything changed since the last write. False when the write failed.</summary>
public bool Flush()
{
byte[] bytes;
long version;
lock (_lock)
{
if (_values == null || _version == _savedVersion) return true;
version = _version;
var buffer = new ArrayBufferWriter<byte>();
using (var w = new Utf8JsonWriter(buffer, FileWriterOptions))
{
w.WriteStartObject();
foreach (var kv in _values.OrderBy(k => k.Key, StringComparer.OrdinalIgnoreCase))
{
w.WritePropertyName(kv.Key);
w.WriteRawValue(kv.Value, skipInputValidation: true);
}
w.WriteEndObject();
}
bytes = buffer.WrittenSpan.ToArray();
}
lock (IoLock)
{
string tmp = _path + ".tmp";
try
{
Directory.CreateDirectory(Path.GetDirectoryName(_path)!);
using (var fs = new FileStream(tmp, FileMode.Create, FileAccess.Write, FileShare.None))
{
fs.Write(bytes, 0, bytes.Length);
fs.Flush(flushToDisk: true);
}
File.Move(tmp, _path, overwrite: true);
}
catch (Exception ex)
{
try { File.Delete(tmp); } catch { }
_warn($"couldn't save {Path.GetFileName(_path)}: {ex.Message}");
return false;
}
}
lock (_lock)
{
if (version > _savedVersion) _savedVersion = version;
// Changes made while writing: start the clock again.
if (_version != _savedVersion && !_disposed) _timer?.Change(DebounceMs, Timeout.Infinite);
}
return true;
}
/// <summary>Script stopped: stop the timer and write what's pending, now.</summary>
public void Dispose()
{
Timer? t;
lock (_lock)
{
_disposed = true;
t = _timer;
_timer = null;
}
t?.Dispose();
Flush();
}
}
/// <summary>File and folder names for the library modules: sanitizing, and resolving a
/// script-supplied relative path so it can never leave its root folder.</summary>
internal static class LibraryPaths
{
private static readonly HashSet<string> ReservedNames = new(StringComparer.OrdinalIgnoreCase)
{
"CON", "PRN", "AUX", "NUL", "CONIN$", "CONOUT$",
"COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8", "COM9",
"LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9",
};
/// <summary>The script's data folder, <c>&lt;dataRoot&gt;\&lt;safe script name&gt;</c>.</summary>
public static string ScriptDataFolder(string dataRoot, string scriptName) =>
Path.Combine(dataRoot, SafeFileName(scriptName));
/// <summary>A single, harmless file name made from <paramref name="name"/> (no separators,
/// no "..", no device names, no trailing dots or spaces).</summary>
public static string SafeFileName(string? name)
{
var invalid = Path.GetInvalidFileNameChars();
var chars = (name ?? string.Empty).Trim().ToCharArray();
for (int i = 0; i < chars.Length; i++)
if (Array.IndexOf(invalid, chars[i]) >= 0 || chars[i] < 32) chars[i] = '_';
string n = new string(chars).TrimEnd('.', ' ');
if (n.Length > 80) n = n[..80].TrimEnd('.', ' ');
if (n.Length == 0 || n.Trim('.').Length == 0) n = "_" + n;
string stem = n.Split('.')[0];
if (ReservedNames.Contains(stem)) n = "_" + n;
return n;
}
/// <summary>
/// The full path of <paramref name="relative"/> under <paramref name="root"/>, or null (with
/// <paramref name="error"/>) when it is absolute, uses a drive, a device name, a stream
/// (":"), wildcards, or climbs out of the root. "" and "." are the root itself.
/// </summary>
public static string? Resolve(string root, string? relative, out string error)
{
error = string.Empty;
string rel = (relative ?? string.Empty).Trim().Replace('/', '\\');
string fullRoot = Path.GetFullPath(root).TrimEnd('\\');
if (rel.Length == 0 || rel == ".") return fullRoot;
if (Path.IsPathRooted(rel) || rel.Contains(':') || rel.StartsWith('\\'))
{
error = $"'{relative}': use a path relative to the folder (no drive letters or leading slashes)";
return null;
}
if (rel.IndexOfAny(new[] { '*', '?', '"', '<', '>', '|' }) >= 0 || rel.Any(ch => ch < 32))
{
error = $"'{relative}': the path has characters a file name can't have";
return null;
}
foreach (string part in rel.Split('\\', StringSplitOptions.RemoveEmptyEntries))
{
string stem = part.TrimEnd('.', ' ').Split('.')[0];
if (ReservedNames.Contains(stem))
{
error = $"'{relative}': '{part}' is a reserved device name";
return null;
}
}
string full = Path.GetFullPath(Path.Combine(fullRoot, rel)).TrimEnd('\\');
if (!full.Equals(fullRoot, StringComparison.OrdinalIgnoreCase)
&& !full.StartsWith(fullRoot + "\\", StringComparison.OrdinalIgnoreCase))
{
error = $"'{relative}': outside the script's folder";
return null;
}
return full;
}
}

View file

@ -0,0 +1,181 @@
using System;
using MoonSharp.Interpreter;
namespace RynthCore.Plugin.RynthLua;
/// <summary>
/// The views module (require("views")): views.Huds.CreateHud(name) -> hud; views.Available;
/// views.Huds.GetIconTexture / GetObjectIconTexture / GetSpellIconTexture (LibraryIcons.cs).
/// The imgui module is in LibraryImGui.cs.
///
/// hud (§1.2): Name, LastError, IsDisposed (read-only); Title, Visible, ShowInBar,
/// WindowSettings, Chrome, DefaultSize, RefreshRate (read/write); OnPreRender / OnRender /
/// OnShow / OnHide (events with Add / Once / Until / Remove); Dispose(). ImGui calls only
/// record into the hud's display list during its render pass (ScriptWindows.cs); results
/// come one pass late.
/// Design: Docs/RYNTHLUA_WINDOWS_DESIGN.md §1.
/// </summary>
public sealed partial class RynthLuaPlugin
{
private const string ViewsRegistryKey = "rynth.views";
// ── views ───────────────────────────────────────────────────────────────
private DynValue CreateViewsModule(Script s, ScriptContext ctx)
{
DynValue cached = s.Registry.Get(ViewsRegistryKey);
if (cached.Type == DataType.Table) return cached;
var views = new Table(s);
var huds = new Table(s);
huds["CreateHud"] = DynValue.NewCallback((c, a) =>
{
var args = LuaArgs.Of(a, huds);
string name = LuaArgs.Str(LuaArgs.At(args, 0)).Trim();
if (name.Length == 0) throw new ScriptRuntimeException("CreateHud(name) needs a name");
// args[1] (icon) is accepted and ignored until icons exist.
ScriptHud hud = CreateHud(ctx, name);
return HudTable(s, hud);
});
AddIconFunctions(s, huds); // GetIconTexture & co. (LibraryIcons.cs)
views["Huds"] = DynValue.NewTable(huds);
var mt = new Table(s);
mt["__index"] = DynValue.NewCallback((c, a) =>
{
string key = a.Count > 1 ? a[1].CastToString() ?? "" : "";
return key == "Available" ? DynValue.NewBoolean(UiAvailable) : DynValue.Nil;
});
views.MetaTable = mt;
DynValue module = DynValue.NewTable(views);
s.Registry.Set(ViewsRegistryKey, module);
return module;
}
/// <summary>The Lua object for a hud (made once per hud; a hud lives in one script state).</summary>
private DynValue HudTable(Script s, ScriptHud hud)
{
if (hud.LuaObject != null) return hud.LuaObject;
var t = new Table(s);
t["OnRender"] = hud.OnRender.CreateTable(s);
t["OnPreRender"] = hud.OnPreRender.CreateTable(s);
t["OnShow"] = hud.OnShow.CreateTable(s);
t["OnHide"] = hud.OnHide.CreateTable(s);
t["Dispose"] = DynValue.NewCallback((c, a) => { DisposeHud(hud); return DynValue.Nil; });
// The events and Dispose live in the table itself; the properties go through the
// metatable; any other key is the script's own field.
var mt = new Table(s);
mt["__index"] = DynValue.NewCallback((c, a) =>
{
string key = a.Count > 1 ? a[1].CastToString() ?? "" : "";
return key switch
{
"Name" => DynValue.NewString(hud.Name),
"Title" => DynValue.NewString(hud.Title),
"Visible" => DynValue.NewBoolean(hud.Visible),
"ShowInBar" => DynValue.NewBoolean(hud.ShowInBar),
"WindowSettings" => DynValue.NewNumber(hud.WindowSettings),
"Chrome" => DynValue.NewString(hud.ChromeNone ? "none" : "standard"),
"DefaultSize" => LibraryImGuiValues.NewVec2(s, hud.DefaultSize.X, hud.DefaultSize.Y),
"RefreshRate" => DynValue.NewNumber(hud.RefreshRate),
"LastError" => hud.LastError == null ? DynValue.Nil : DynValue.NewString(hud.LastError),
"IsDisposed" => DynValue.NewBoolean(hud.Disposed),
_ => DynValue.Nil,
};
});
mt["__newindex"] = DynValue.NewCallback((c, a) =>
{
string key = a.Count > 1 ? a[1].CastToString() ?? "" : "";
DynValue v = a.Count > 2 ? a[2] : DynValue.Nil;
switch (key)
{
case "Title":
SetHudTitle(hud, LuaArgs.Str(v, hud.Name));
break;
case "Visible":
// The script's own choice: it applies (OnShow/OnHide fire) and goes to the
// engine with the next submit, but it is NOT remembered as the player's.
SetHudVisible(hud, v.CastToBool());
break;
case "ShowInBar":
{
bool show = v.CastToBool();
if (hud.ShowInBar != show) { hud.ShowInBar = show; hud.PropsDirty = true; }
break;
}
case "WindowSettings":
SetHudWindowSettings(hud, WindowSettingsArg(v));
break;
case "Chrome":
{
string chrome = v.Type == DataType.String ? v.String.Trim().ToLowerInvariant() : "";
if (chrome is not ("standard" or "none"))
throw new ScriptRuntimeException($"hud.Chrome must be \"standard\" or \"none\", not {DescribeValue(v)}");
bool none = chrome == "none";
if (hud.ChromeNone != none) { hud.ChromeNone = none; hud.PropsDirty = true; hud.PassNow = true; }
break;
}
case "DefaultSize":
{
// The same as SetNextWindowSize(size, ImGuiCond.FirstUseEver): used by the engine
// only while nothing is saved for the window. nil resets it to the engine default.
System.Numerics.Vector2 size = System.Numerics.Vector2.Zero;
if (!v.IsNil())
{
if (!LibraryImGuiValues.TryVec2(v, out float x, out float y))
throw new ScriptRuntimeException($"hud.DefaultSize must be a Vector2 or {{x, y}}, not {DescribeValue(v)}");
size = Finite(new System.Numerics.Vector2(x, y)); // the header sends non-finite as 0 anyway
}
if (hud.DefaultSize != size) { hud.DefaultSize = size; hud.PropsDirty = true; }
break;
}
case "RefreshRate":
{
// Passes per second while visible, clamped to 1..60 (a pass after input
// comes on the next tick whatever the rate).
double d = v.IsNil() ? DefaultRefreshRate : LuaArgs.Num(v, double.NaN);
if (double.IsNaN(d))
throw new ScriptRuntimeException($"hud.RefreshRate must be a number (1 to {MaxRefreshRate}), not {DescribeValue(v)}");
int rate = (int)Math.Clamp(Math.Round(d), MinRefreshRate, MaxRefreshRate);
if (hud.RefreshRate != rate)
{
hud.RefreshRate = rate;
hud.NextPassAt = 0; // the new rate starts now
}
break;
}
case "Name":
case "LastError":
case "IsDisposed":
throw new ScriptRuntimeException($"hud.{key} is read-only");
default:
t.Set(a[1], v); // the script's own field
break;
}
return DynValue.Nil;
});
mt["__tostring"] = DynValue.NewCallback((c, a) => DynValue.NewString($"Hud {hud.Name}"));
t.MetaTable = mt;
hud.LuaObject = DynValue.NewTable(t);
return hud.LuaObject;
}
/// <summary>hud.WindowSettings: an ImGuiWindowFlags number (0 or nil = none).</summary>
private static long WindowSettingsArg(DynValue v)
{
if (v.IsNil()) return 0;
double d = v.Type == DataType.Number ? v.Number : double.NaN;
if (!double.IsFinite(d) || d < 0 || d > uint.MaxValue || Math.Floor(d) != d)
throw new ScriptRuntimeException($"hud.WindowSettings must be ImGuiWindowFlags (a whole number), not {DescribeValue(v)}");
return (long)d;
}
private static string DescribeValue(DynValue v) =>
v.Type == DataType.String ? $"\"{(v.String.Length > 40 ? v.String[..40] + "..." : v.String)}\""
: v.Type == DataType.Number ? v.Number.ToString(System.Globalization.CultureInfo.InvariantCulture)
: v.Type.ToLuaTypeString();
}

View file

@ -0,0 +1,216 @@
using System;
using System.Globalization;
using MoonSharp.Interpreter;
using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthLua;
/// <summary>
/// The globals every script sees (besides Lua's libraries and LuaScriptHost's scheduler
/// globals). Kept exactly as they were when Lua lived in RynthAi, so existing scripts run:
///
/// print(...) → Lua panel console
/// chat(text) → your chat window only
/// command(text) → as if typed in chat: /ra, /ub, /mt, /say, /f, ...
/// expr(expression) → a meta expression, e.g. expr("getcharvital_current[1]")
/// meta.&lt;function&gt;(args...) → any meta expression function by name
/// getvar(name) / setvar(name, value) → meta session variables (shared with metas)
/// me.name, me.id, me.health, me.maxhealth, me.stamina, me.maxstamina,
/// me.mana, me.maxmana, me.landcell, me.coords
/// RynthAi:GoTo / Stop / UsePortal / GetDistance / GetPlayerNS / GetPlayerEW / GetPlayerZ / IsPathClear
/// Settings.&lt;name&gt; read or set any RynthAi setting metas can use
/// function OnBotTick() end called every 250 ms while the RynthAi macro runs
///
/// Meta expressions, settings, the macro, navigation, object search and line of sight
/// are RynthAi's: they come through RynthAiBridge and raise a Lua error when RynthAi
/// isn't loaded. The rest only needs RynthCore.
/// </summary>
public sealed partial class RynthLuaPlugin
{
private void RegisterV1Api(Script s, LuaScriptHost host)
{
s.Globals["chat"] = DynValue.NewCallback((ctx, a) =>
{
if (Host.HasWriteToChat) Host.WriteToChat(JoinArgs(a), 1);
return DynValue.Nil;
});
s.Globals["command"] = DynValue.NewCallback((ctx, a) =>
{
string text = JoinArgs(a).Trim();
if (text.Length > 0) _ai.SubmitCommand(text);
return DynValue.Nil;
});
s.Globals["expr"] = DynValue.NewCallback((ctx, a) =>
EvalExpression(a.Count > 0 ? a[0].CastToString() ?? "" : ""));
s.Globals["getvar"] = DynValue.NewCallback((ctx, a) => CallMeta("getvar", a));
s.Globals["setvar"] = DynValue.NewCallback((ctx, a) => CallMeta("setvar", a));
// meta.<name>(...): any expression function, looked up on first use.
var meta = new Table(s);
var metaMt = new Table(s);
metaMt["__index"] = DynValue.NewCallback((ctx, a) =>
{
string fn = a.Count > 1 ? a[1].CastToString() ?? "" : "";
if (fn.Length == 0) return DynValue.Nil;
return DynValue.NewCallback((_, args) => CallMeta(fn, args));
});
meta.MetaTable = metaMt;
s.Globals["meta"] = DynValue.NewTable(meta);
// me.<field>: read live each time.
var me = new Table(s);
var meMt = new Table(s);
meMt["__index"] = DynValue.NewCallback((ctx, a) =>
{
string key = (a.Count > 1 ? a[1].CastToString() ?? "" : "").ToLowerInvariant();
return key switch
{
"name" => EvalExpression("wobjectgetname[wobjectgetplayer[]]"),
"id" => DynValue.NewNumber(Host.GetPlayerId()),
"health" => EvalExpression("getcharvital_current[1]"),
"stamina" => EvalExpression("getcharvital_current[2]"),
"mana" => EvalExpression("getcharvital_current[3]"),
"maxhealth" => EvalExpression("getcharvital_buffedmax[1]"),
"maxstamina" => EvalExpression("getcharvital_buffedmax[2]"),
"maxmana" => EvalExpression("getcharvital_buffedmax[3]"),
"landcell" => EvalExpression("getplayerlandcell[]"),
"coords" => EvalExpression("coordinatetostring[getplayercoordinates[]]"),
_ => DynValue.Nil,
};
});
me.MetaTable = meMt;
s.Globals["me"] = DynValue.NewTable(me);
RegisterCompatApi(s, host);
}
private static string JoinArgs(CallbackArguments a)
{
var parts = new string[a.Count];
for (int i = 0; i < a.Count; i++) parts[i] = a[i].ToPrintString();
return string.Join(" ", parts);
}
/// <summary>Calls meta function <paramref name="fn"/> with Lua args quoted as literals.</summary>
private DynValue CallMeta(string fn, CallbackArguments args)
{
var quoted = new string[args.Count];
for (int i = 0; i < args.Count; i++)
{
DynValue v = args[i];
quoted[i] = v.Type switch
{
DataType.Number => v.Number.ToString("R", CultureInfo.InvariantCulture),
DataType.Boolean => v.Boolean ? "1" : "0",
DataType.Nil => "",
// Backticks make the meta parser take the text as-is (commas and
// brackets included); a backtick inside would end it early.
_ => "`" + (v.CastToString() ?? "").Replace('`', '\'') + "`",
};
}
return EvalExpression($"{fn}[{string.Join(",", quoted)}]");
}
/// <summary>A meta expression through RynthAi; numbers come back as Lua numbers.</summary>
private DynValue EvalExpression(string expression)
{
if (!_ai.Evaluate(expression, out string r))
throw new ScriptRuntimeException(r == RynthAiBridge.NotLoaded ? r : $"{expression}: {r}");
if (double.TryParse(r, NumberStyles.Float, CultureInfo.InvariantCulture, out double d))
return DynValue.NewNumber(d);
return DynValue.NewString(r);
}
// ── The Decal RynthAi's script surface ──────────────────────────────────
private void RegisterCompatApi(Script s, LuaScriptHost host)
{
var ra = new Table(s);
// Methods are called with a colon, so argument 0 is the table itself.
ra["GoTo"] = DynValue.NewCallback((ctx, a) =>
{
double ns = ParseCoord(a.Count > 1 ? a[1] : DynValue.Nil, 'N', 'S');
double ew = ParseCoord(a.Count > 2 ? a[2] : DynValue.Nil, 'E', 'W');
if (!_ai.GoTo(ns, ew)) throw new ScriptRuntimeException("GoTo: " + RynthAiBridge.NotLoaded);
ChatLine($"Going to {Math.Abs(ns):F2}{(ns < 0 ? "S" : "N")}, {Math.Abs(ew):F2}{(ew < 0 ? "W" : "E")}");
return DynValue.Nil;
});
ra["Stop"] = DynValue.NewCallback((_, _) => { _ai.Stop(); return DynValue.Nil; });
ra["UsePortal"] = DynValue.NewCallback((ctx, a) =>
{
string name = a.Count > 1 ? a[1].CastToString() ?? "" : "";
if (!_ai.FindNearest(name, portalOrNpcOnly: true, out uint id, out _))
{
host.Print($"UsePortal: no portal or NPC named like '{name}' nearby.");
return DynValue.False;
}
return DynValue.NewBoolean(Host.UseFor(id, "Script", $"ra.UsePortal('{name}')", UseKind.Asked));
});
ra["GetDistance"] = DynValue.NewCallback((ctx, a) =>
{
string name = a.Count > 1 ? a[1].CastToString() ?? "" : "";
return DynValue.NewNumber(_ai.FindNearest(name, portalOrNpcOnly: false, out _, out double d) ? d : -1);
});
ra["GetPlayerNS"] = DynValue.NewCallback((_, _) =>
DynValue.NewNumber(NavCoordinateHelper.TryGetNavCoords(Host, out double ns, out _) ? ns : 0));
ra["GetPlayerEW"] = DynValue.NewCallback((_, _) =>
DynValue.NewNumber(NavCoordinateHelper.TryGetNavCoords(Host, out _, out double ew) ? ew : 0));
ra["GetPlayerZ"] = DynValue.NewCallback((_, _) =>
DynValue.NewNumber(Host.HasGetPlayerPose && Host.TryGetPlayerPose(out _, out _, out _, out float z, out _, out _, out _, out _) ? z : 0));
ra["IsPathClear"] = DynValue.NewCallback((ctx, a) =>
{
DynValue t = a.Count > 1 ? a[1] : DynValue.Nil;
uint id = 0;
if (t.Type == DataType.Number) id = (uint)t.Number;
else _ai.FindNearest(t.CastToString() ?? "", portalOrNpcOnly: false, out id, out _);
if (id == 0) throw new ScriptRuntimeException("IsPathClear(target): no target by that name or id");
return DynValue.NewBoolean(_ai.IsPathClear(id));
});
s.Globals["RynthAi"] = DynValue.NewTable(ra);
// Settings.<name>: the same settings map metas use for getsetting/setsetting.
var settings = new Table(s);
var mt = new Table(s);
mt["__index"] = DynValue.NewCallback((ctx, a) =>
{
string key = a.Count > 1 ? a[1].CastToString() ?? "" : "";
string? v = _ai.GetSetting(key);
if (v == null) return DynValue.Nil;
return double.TryParse(v, NumberStyles.Float, CultureInfo.InvariantCulture, out double d)
? DynValue.NewNumber(d) : DynValue.NewString(v);
});
mt["__newindex"] = DynValue.NewCallback((ctx, a) =>
{
string key = a.Count > 1 ? a[1].CastToString() ?? "" : "";
DynValue v = a.Count > 2 ? a[2] : DynValue.Nil;
string text = v.Type switch
{
DataType.Boolean => v.Boolean ? "1" : "0",
DataType.Number => v.Number.ToString("R", CultureInfo.InvariantCulture),
_ => v.CastToString() ?? "",
};
if (!_ai.SetSetting(key, text))
throw new ScriptRuntimeException(_ai.Available ? $"Settings.{key}: no such setting" : RynthAiBridge.NotLoaded);
return DynValue.Nil;
});
settings.MetaTable = mt;
s.Globals["Settings"] = DynValue.NewTable(settings);
}
/// <summary>"33.5N" / "44.8W" / a number → signed nav coordinate (S and W negative).</summary>
private static double ParseCoord(DynValue v, char pos, char neg)
{
if (v.Type == DataType.Number) return v.Number;
string t = (v.CastToString() ?? "").Trim().ToUpperInvariant();
double sign = 1;
if (t.EndsWith(neg)) { sign = -1; t = t[..^1]; }
else if (t.EndsWith(pos)) t = t[..^1];
if (!double.TryParse(t.Trim(), NumberStyles.Float, CultureInfo.InvariantCulture, out double d))
throw new ScriptRuntimeException($"GoTo: can't read coordinate '{v.CastToString()}' (use e.g. \"33.5N\", \"44.8W\")");
return sign * d;
}
}

View file

@ -0,0 +1,836 @@
// Generated from the enum definitions UtilityBelt scripts use (AC protocol enums, whose names
// and values match ACE's, and UtilityBelt's scripting enums): names and numbers only.
// Regenerate rather than edit by hand. The property-id enums RynthLua already had (IntId,
// BoolId, StringId), ObjectClass, SkillId, AttributeId, VitalId, CombatMode and ChatType
// live in LibraryEnums.cs / LuaEnums.cs.
namespace RynthCore.Plugin.RynthLua;
internal static class LuaEnumData
{
/// <summary>(enum name, is a flags enum, members in declaration order).</summary>
public static readonly (string Name, bool Flags, (string, long)[] Members)[] All =
{
("AmmoType", false, new (string, long)[]
{
("ThrownWeapon", 0), ("Arrow", 1), ("Bolt", 2), ("Dart", 4),
}),
("AttackHeight", false, new (string, long)[]
{
("High", 1), ("Medium", 2), ("Low", 3),
}),
("CharacterOptions1", true, new (string, long)[]
{
("u_0x00000001", 1), ("u_0x00000002", 2), ("u_0x00000004", 4), ("u_0x00000008", 8), ("u_0x00000010", 16),
("u_0x00000020", 32), ("u_0x00000040", 64), ("u_0x00000080", 128), ("u_0x00000100", 256),
("u_0x00000200", 512), ("u_0x00000400", 1024), ("u_0x00000800", 2048), ("u_0x00001000", 4096),
("u_0x00002000", 8192), ("u_0x00004000", 16384), ("u_0x00008000", 32768), ("u_0x00010000", 65536),
("u_0x00020000", 131072), ("u_0x00040000", 262144), ("u_0x00080000", 524288), ("u_0x00100000", 1048576),
("u_0x00200000", 2097152), ("u_0x00400000", 4194304), ("u_0x00800000", 8388608),
("u_0x01000000", 16777216), ("u_0x02000000", 33554432), ("u_0x04000000", 67108864),
("u_0x08000000", 134217728), ("u_0x10000000", 268435456), ("u_0x20000000", 536870912),
("u_0x40000000", 1073741824), ("u_0x80000000", 2147483648),
}),
("CharacterOptions2", true, new (string, long)[]
{
("u_0x00000001", 1), ("u_0x00000002", 2), ("u_0x00000004", 4), ("u_0x00000008", 8), ("u_0x00000010", 16),
("u_0x00000020", 32), ("u_0x00000040", 64), ("u_0x00000080", 128), ("u_0x00000100", 256),
("u_0x00000200", 512), ("u_0x00000400", 1024), ("u_0x00000800", 2048), ("u_0x00002000", 8192),
("u_0x00004000", 16384), ("u_0x00008000", 32768), ("u_0x00010000", 65536), ("u_0x00020000", 131072),
("u_0x00040000", 262144),
}),
("ContainerProperties", false, new (string, long)[]
{
("None", 0), ("Container", 1), ("Foci", 2),
}),
("CoverageMask", true, new (string, long)[]
{
("UpperLegsUnderwear", 2), ("LowerLegsUnderwear", 4), ("ChestUnderwear", 8), ("AbdomenUnderwear", 16),
("UpperArmsUnderwear", 32), ("LowerArmsUnderwear", 64), ("UpperLegs", 256), ("LowerLegs", 512),
("Chest", 1024), ("Abdomen", 2048), ("UpperArms", 4096), ("LowerArms", 8192), ("Head", 16384),
("Hands", 32768), ("Feet", 65536),
}),
("CreatureType", false, new (string, long)[]
{
("Invalid", 0), ("Olthoi", 1), ("Banderling", 2), ("Drudge", 3), ("Mosswart", 4), ("Lugian", 5),
("Tumerok", 6), ("Mite", 7), ("Tusker", 8), ("PhyntosWasp", 9), ("Rat", 10), ("Auroch", 11), ("Cow", 12),
("Golem", 13), ("Undead", 14), ("Gromnie", 15), ("Reedshark", 16), ("Armoredillo", 17), ("Fae", 18),
("Virindi", 19), ("Wisp", 20), ("Knathtead", 21), ("Shadow", 22), ("Mattekar", 23), ("Mumiyah", 24),
("Rabbit", 25), ("Sclavus", 26), ("ShallowsShark", 27), ("Monouga", 28), ("Zefir", 29), ("Skeleton", 30),
("Human", 31), ("Shreth", 32), ("Chittick", 33), ("Moarsman", 34), ("OlthoiLarvae", 35), ("Slithis", 36),
("Deru", 37), ("FireElemental", 38), ("Snowman", 39), ("Unknown", 40), ("Bunny", 41),
("LightningElemental", 42), ("Rockslide", 43), ("Grievver", 44), ("Niffis", 45), ("Ursuin", 46),
("Crystal", 47), ("HollowMinion", 48), ("Scarecrow", 49), ("Idol", 50), ("Empyrean", 51),
("Hopeslayer", 52), ("Doll", 53), ("Marionette", 54), ("Carenzi", 55), ("Siraluun", 56),
("AunTumerok", 57), ("HeaTumerok", 58), ("Simulacrum", 59), ("AcidElemental", 60),
("FrostElemental", 61), ("Elemental", 62), ("Statue", 63), ("Wall", 64), ("AlteredHuman", 65),
("Device", 66), ("Harbinger", 67), ("DarkSarcophagus", 68), ("Chicken", 69), ("GotrokLugian", 70),
("Margul", 71), ("BleachedRabbit", 72), ("NastyRabbit", 73), ("GrimacingRabbit", 74), ("Burun", 75),
("Target", 76), ("Ghost", 77), ("Fiun", 78), ("Eater", 79), ("Penguin", 80), ("Ruschk", 81),
("Thrungus", 82), ("ViamontianKnight", 83), ("Remoran", 84), ("Swarm", 85), ("Moar", 86),
("EnchantedArms", 87), ("Sleech", 88), ("Mukkir", 89), ("Merwart", 90), ("Food", 91),
("ParadoxOlthoi", 92), ("Harvest", 93), ("Energy", 94), ("Apparition", 95), ("Aerbax", 96),
("Touched", 97), ("BlightedMoarsman", 98), ("GearKnight", 99), ("Gurog", 100), ("Anekshay", 101),
}),
("DamageType", true, new (string, long)[]
{
("Slashing", 1), ("Piercing", 2), ("Bludgeoning", 4), ("Cold", 8), ("Fire", 16), ("Acid", 32),
("Electric", 64),
}),
("DataId", false, new (string, long)[]
{
("Undef", 0), ("Setup", 1), ("MotionTable", 2), ("SoundTable", 3), ("CombatTable", 4),
("QualityFilter", 5), ("PaletteBase", 6), ("ClothingBase", 7), ("Icon", 8), ("EyesTexture", 9),
("NoseTexture", 10), ("MouthTexture", 11), ("DefaultEyesTexture", 12), ("DefaultNoseTexture", 13),
("DefaultMouthTexture", 14), ("HairPalette", 15), ("EyesPalette", 16), ("SkinPalette", 17),
("HeadObject", 18), ("ActivationAnimation", 19), ("InitMotion", 20), ("ActivationSound", 21),
("PhysicsEffectTable", 22), ("UseSound", 23), ("UseTargetAnimation", 24),
("UseTargetSuccessAnimation", 25), ("UseTargetFailureAnimation", 26), ("UseUserAnimation", 27),
("Spell", 28), ("SpellComponent", 29), ("PhysicsScript", 30), ("LinkedPortalOne", 31),
("WieldedTreasureType", 32), ("UnknownGuessedname", 33), ("UnknownGuessedname2", 34),
("DeathTreasureType", 35), ("MutateFilter", 36), ("ItemSkillLimit", 37), ("UseCreateItem", 38),
("DeathSpell", 39), ("VendorsClassId", 40), ("ItemSpecializedOnly", 41), ("HouseId", 42),
("AccountHouseId", 43), ("RestrictionEffect", 44), ("CreationMutationFilter", 45),
("TsysMutationFilter", 46), ("LastPortal", 47), ("LinkedPortalTwo", 48), ("OriginalPortal", 49),
("IconOverlay", 50), ("IconOverlaySecondary", 51), ("IconUnderlay", 52),
("AugmentationMutationFilter", 53), ("AugmentationEffect", 54), ("ProcSpell", 55),
("AugmentationCreateItem", 56), ("AlternateCurrency", 57), ("BlueSurgeSpell", 58),
("YellowSurgeSpell", 59), ("RedSurgeSpell", 60), ("OlthoiDeathTreasureType", 61),
}),
("EnchantmentFlags", false, new (string, long)[]
{
("Undef", 0), ("Attribute", 1), ("Attribute2nd", 2), ("Int", 4), ("Float", 8), ("Skill", 16),
("BodyDamageValue", 32), ("BodyDamageVariance", 64), ("BodyArmorValue", 128), ("SingleStat", 4096),
("MultipleStat", 8192), ("Multiplicative", 16384), ("Additive", 32768), ("AttackSkills", 65536),
("DefenseSkills", 131072), ("Multiplicative_Degrade", 1048576), ("Additive_Degrade", 2097152),
("Vitae", 8388608), ("Cooldown", 16777216), ("Beneficial", 33554432), ("StatTypes", 255),
}),
("EndTradeReason", false, new (string, long)[]
{
("Normal", 0), ("EnteredCombat", 2), ("Cancelled", 81),
}),
("EquipMask", true, new (string, long)[]
{
("None", 0), ("Head", 1), ("ChestUnderwear", 2), ("AbdomenUnderwear", 4), ("UpperArmsUnderwear", 8),
("LowerArmsUnderwear", 16), ("Hands", 32), ("UpperLegsUnderwear", 64), ("LowerLegsUnderwear", 128),
("Feet", 256), ("Chest", 512), ("Abdomen", 1024), ("UpperArms", 2048), ("LowerArms", 4096),
("UpperLegs", 8192), ("LowerLegs", 16384), ("Necklace", 32768), ("RightBracelet", 65536),
("LeftBracelet", 131072), ("RightRing", 262144), ("LeftRing", 524288), ("MeleeWeapon", 1048576),
("Shield", 2097152), ("MissileWeapon", 4194304), ("Ammunition", 8388608), ("Wand", 16777216),
("Cloak", 134217728), ("Trinket", 67108864), ("BlueAetheria", 268435456), ("YellowAetheria", 536870912),
("RedAetheria", 1073741824),
}),
("FloatId", false, new (string, long)[]
{
("Undef", 0), ("HeartbeatInterval", 1), ("HeartbeatTimestamp", 2), ("HealthRate", 3), ("StaminaRate", 4),
("ManaRate", 5), ("HealthUponResurrection", 6), ("StaminaUponResurrection", 7),
("ManaUponResurrection", 8), ("StartTime", 9), ("StopTime", 10), ("ResetInterval", 11), ("Shade", 12),
("ArmorModVsSlash", 13), ("ArmorModVsPierce", 14), ("ArmorModVsBludgeon", 15), ("ArmorModVsCold", 16),
("ArmorModVsFire", 17), ("ArmorModVsAcid", 18), ("ArmorModVsElectric", 19), ("CombatSpeed", 20),
("WeaponLength", 21), ("DamageVariance", 22), ("CurrentPowerMod", 23), ("AccuracyMod", 24),
("StrengthMod", 25), ("MaximumVelocity", 26), ("RotationSpeed", 27), ("MotionTimestamp", 28),
("WeaponDefense", 29), ("WimpyLevel", 30), ("VisualAwarenessRange", 31), ("AuralAwarenessRange", 32),
("PerceptionLevel", 33), ("PowerupTime", 34), ("MaxChargeDistance", 35), ("ChargeSpeed", 36),
("BuyPrice", 37), ("SellPrice", 38), ("DefaultScale", 39), ("LockpickMod", 40),
("RegenerationInterval", 41), ("RegenerationTimestamp", 42), ("GeneratorRadius", 43), ("TimeToRot", 44),
("DeathTimestamp", 45), ("PkTimestamp", 46), ("VictimTimestamp", 47), ("LoginTimestamp", 48),
("CreationTimestamp", 49), ("MinimumTimeSincePk", 50), ("DeprecatedHousekeepingPriority", 51),
("AbuseLoggingTimestamp", 52), ("LastPortalTeleportTimestamp", 53), ("UseRadius", 54),
("HomeRadius", 55), ("ReleasedTimestamp", 56), ("MinHomeRadius", 57), ("Facing", 58),
("ResetTimestamp", 59), ("LogoffTimestamp", 60), ("EconRecoveryInterval", 61), ("WeaponOffense", 62),
("DamageMod", 63), ("ResistSlash", 64), ("ResistPierce", 65), ("ResistBludgeon", 66), ("ResistFire", 67),
("ResistCold", 68), ("ResistAcid", 69), ("ResistElectric", 70), ("ResistHealthBoost", 71),
("ResistStaminaDrain", 72), ("ResistStaminaBoost", 73), ("ResistManaDrain", 74), ("ResistManaBoost", 75),
("Translucency", 76), ("PhysicsScriptIntensity", 77), ("Friction", 78), ("Elasticity", 79),
("AiUseMagicDelay", 80), ("ItemMinSpellcraftMod", 81), ("ItemMaxSpellcraftMod", 82),
("ItemRankProbability", 83), ("Shade2", 84), ("Shade3", 85), ("Shade4", 86), ("ItemEfficiency", 87),
("ItemManaUpdateTimestamp", 88), ("SpellGestureSpeedMod", 89), ("SpellStanceSpeedMod", 90),
("AllegianceAppraisalTimestamp", 91), ("PowerLevel", 92), ("AccuracyLevel", 93), ("AttackAngle", 94),
("AttackTimestamp", 95), ("CheckpointTimestamp", 96), ("SoldTimestamp", 97), ("UseTimestamp", 98),
("UseLockTimestamp", 99), ("HealkitMod", 100), ("FrozenTimestamp", 101), ("HealthRateMod", 102),
("AllegianceSwearTimestamp", 103), ("ObviousRadarRange", 104), ("HotspotCycleTime", 105),
("HotspotCycleTimeVariance", 106), ("SpamTimestamp", 107), ("SpamRate", 108),
("BondWieldedTreasure", 109), ("BulkMod", 110), ("SizeMod", 111), ("GagTimestamp", 112),
("GeneratorUpdateTimestamp", 113), ("DeathSpamTimestamp", 114), ("DeathSpamRate", 115),
("WildAttackProbability", 116), ("FocusedProbability", 117), ("CrashAndTurnProbability", 118),
("CrashAndTurnRadius", 119), ("CrashAndTurnBias", 120), ("GeneratorInitialDelay", 121),
("AiAcquireHealth", 122), ("AiAcquireStamina", 123), ("AiAcquireMana", 124), ("ResistHealthDrain", 125),
("LifestoneProtectionTimestamp", 126), ("AiCounteractEnchantment", 127), ("AiDispelEnchantment", 128),
("TradeTimestamp", 129), ("AiTargetedDetectionRadius", 130), ("EmotePriority", 131),
("LastTeleportStartTimestamp", 132), ("EventSpamTimestamp", 133), ("EventSpamRate", 134),
("InventoryOffset", 135), ("CriticalMultiplier", 136), ("ManaStoneDestroyChance", 137),
("SlayerDamageBonus", 138), ("AllegianceInfoSpamTimestamp", 139), ("AllegianceInfoSpamRate", 140),
("NextSpellcastTimestamp", 141), ("AppraisalRequestedTimestamp", 142),
("AppraisalHeartbeatDueTimestamp", 143), ("ManaConversionMod", 144), ("LastPkAttackTimestamp", 145),
("FellowshipUpdateTimestamp", 146), ("CriticalFrequency", 147), ("LimboStartTimestamp", 148),
("WeaponMissileDefense", 149), ("WeaponMagicDefense", 150), ("IgnoreShield", 151),
("ElementalDamageMod", 152), ("StartMissileAttackTimestamp", 153), ("LastRareUsedTimestamp", 154),
("IgnoreArmor", 155), ("ProcSpellRate", 156), ("ResistanceModifier", 157),
("AllegianceGagTimestamp", 158), ("AbsorbMagicDamage", 159), ("CachedMaxAbsorbMagicDamage", 160),
("GagDuration", 161), ("AllegianceGagDuration", 162), ("GlobalXpMod", 163), ("HealingModifier", 164),
("ArmorModVsNether", 165), ("ResistNether", 166), ("CooldownDuration", 167), ("WeaponAuraOffense", 168),
("WeaponAuraDefense", 169), ("WeaponAuraElemental", 170), ("WeaponAuraManaConv", 171),
}),
("Gender", false, new (string, long)[]
{
("Invalid", 0), ("Male", 1), ("Female", 2),
}),
("HeritageGroup", false, new (string, long)[]
{
("Invalid", 0), ("Aluvian", 1), ("Gharundim", 2), ("Sho", 3), ("Viamontian", 4), ("Shadowbound", 5),
("Gearknight", 6), ("Tumerok", 7), ("Lugian", 8), ("Empyrean", 9), ("Penumbraen", 10), ("Undead", 11),
("Olthoi", 12), ("OlthoiAcid", 13),
}),
("IconHighlight", true, new (string, long)[]
{
("Invalid", 0), ("Magical", 1), ("Poisoned", 2), ("BoostHealth", 4), ("BoostMana", 8),
("BoostStamina", 16), ("Fire", 32), ("Lightning", 64), ("Frost", 128), ("Acid", 256),
("Bludgeoning", 512), ("Slashing", 1024), ("Piercing", 2048), ("Nether", 4096),
}),
("InstanceId", false, new (string, long)[]
{
("Undef", 0), ("Owner", 1), ("Container", 2), ("Wielder", 3), ("Freezer", 4), ("Viewer", 5),
("Generator", 6), ("Scribe", 7), ("CurrentCombatTarget", 8), ("CurrentEnemy", 9),
("ProjectileLauncher", 10), ("CurrentAttacker", 11), ("CurrentDamager", 12), ("CurrentFollowTarget", 13),
("CurrentAppraisalTarget", 14), ("CurrentFellowshipAppraisalTarget", 15), ("ActivationTarget", 16),
("Creator", 17), ("Victim", 18), ("Killer", 19), ("Vendor", 20), ("Customer", 21), ("Bonded", 22),
("Wounder", 23), ("Allegiance", 24), ("Patron", 25), ("Monarch", 26), ("CombatTarget", 27),
("HealthQueryTarget", 28), ("LastUnlocker", 29), ("CrashAndTurnTarget", 30), ("AllowedActivator", 31),
("HouseOwner", 32), ("House", 33), ("Slumlord", 34), ("ManaQueryTarget", 35), ("CurrentGame", 36),
("RequestedAppraisalTarget", 37), ("AllowedWielder", 38), ("AssignedTarget", 39), ("LimboSource", 40),
("Snooper", 41), ("TeleportedCharacter", 42), ("Pet", 43), ("PetOwner", 44), ("PetDevice", 45),
}),
("Int64Id", false, new (string, long)[]
{
("Undef", 0), ("TotalExperience", 1), ("AvailableExperience", 2), ("AugmentationCost", 3),
("ItemTotalXp", 4), ("ItemBaseXp", 5), ("AvailableLuminance", 6), ("MaximumLuminance", 7),
("InteractionReqs", 8),
}),
("MagicSchool", false, new (string, long)[]
{
("None", 0), ("WarMagic", 1), ("LifeMagic", 2), ("ItemEnchantment", 3), ("CreatureEnchantment", 4),
("VoidMagic", 5),
}),
("MaterialType", false, new (string, long)[]
{
("Ceramic", 1), ("Porcelain", 2), ("Linen", 4), ("Satin", 5), ("Silk", 6), ("Velvet", 7), ("Wool", 8),
("Agate", 10), ("Amber", 11), ("Amethyst", 12), ("Aquamarine", 13), ("Azurite", 14), ("BlackGarnet", 15),
("BlackOpal", 16), ("Bloodstone", 17), ("Carnelian", 18), ("Citrine", 19), ("Diamond", 20),
("Emerald", 21), ("FireOpal", 22), ("GreenGarnet", 23), ("GreenJade", 24), ("Hematite", 25),
("ImperialTopaz", 26), ("Jet", 27), ("LapisLazuli", 28), ("LavenderJade", 29), ("Malachite", 30),
("Moonstone", 31), ("Onyx", 32), ("Opal", 33), ("Peridot", 34), ("RedGarnet", 35), ("RedJade", 36),
("RoseQuartz", 37), ("Ruby", 38), ("Sapphire", 39), ("SmokeyQuartz", 40), ("Sunstone", 41),
("TigerEye", 42), ("Tourmaline", 43), ("Turquoise", 44), ("WhiteJade", 45), ("WhiteQuartz", 46),
("WhiteSapphire", 47), ("YellowGarnet", 48), ("YellowTopaz", 49), ("Zircon", 50), ("Ivory", 51),
("Leather", 52), ("ArmoredilloHide", 53), ("GromnieHide", 54), ("ReedSharkHide", 55), ("Brass", 57),
("Bronze", 58), ("Copper", 59), ("Gold", 60), ("Iron", 61), ("Pyreal", 62), ("Silver", 63),
("Steel", 64), ("Alabaster", 66), ("Granite", 67), ("Marble", 68), ("Obsidian", 69), ("Sandstone", 70),
("Serpentine", 71), ("Ebony", 73), ("Mahogany", 74), ("Oak", 75), ("Pine", 76), ("Teak", 77),
}),
("MotionStance", false, new (string, long)[]
{
("HandCombat", 60), ("NonCombat", 61), ("SwordCombat", 62), ("BowCombat", 63), ("SwordShieldCombat", 64),
("CrossbowCombat", 65), ("UnusedCombat", 66), ("SlingCombat", 67), ("TwoHandedSwordCombat", 68),
("TwoHandedStaffCombat", 69), ("DualWieldCombat", 70), ("ThrownWeaponCombat", 71), ("Magic", 73),
("BowNoAmmo", 232), ("CrossBowNoAmmo", 233), ("AtlatlCombat", 312), ("ThrownShieldCombat", 313),
}),
("ObjectDescriptionFlag", true, new (string, long)[]
{
("Openable", 1), ("Inscribable", 2), ("Stuck", 4), ("Player", 8), ("Attackable", 16),
("PlayerKiller", 32), ("HiddenAdmin", 64), ("UiHidden", 128), ("Book", 256), ("Vendor", 512),
("PkSwitch", 1024), ("NpkSwitch", 2048), ("Door", 4096), ("Corpse", 8192), ("LifeStone", 16384),
("Food", 32768), ("Healer", 65536), ("Lockpick", 131072), ("Portal", 262144), ("Admin", 1048576),
("FreePkStatus", 2097152), ("ImmuneCellRestrictions", 4194304), ("RequiresPackSlot", 8388608),
("Retained", 16777216), ("PkLiteStatus", 33554432), ("IncludesSecondHeader", 67108864),
("BindStone", 134217728), ("VolatileRare", 268435456), ("WieldOnUse", 536870912),
("WieldLeft", 1073741824),
}),
("ObjectType", true, new (string, long)[]
{
("MeleeWeapon", 1), ("Armor", 2), ("Clothing", 4), ("Jewelry", 8), ("Creature", 16), ("Food", 32),
("Money", 64), ("Misc", 128), ("MissileWeapon", 256), ("Container", 512), ("Useless", 1024),
("Gem", 2048), ("SpellComponents", 4096), ("Writable", 8192), ("Key", 16384), ("Caster", 32768),
("Portal", 65536), ("Lockable", 131072), ("PromissoryNote", 262144), ("ManaStone", 524288),
("Service", 1048576), ("MagicWieldable", 2097152), ("CraftCookingBase", 4194304),
("CraftAlchemyBase", 8388608), ("CraftFletchingBase", 33554432), ("CraftAlchemyIntermediate", 67108864),
("CraftFletchingIntermediate", 134217728), ("LifeStone", 268435456), ("TinkeringTool", 536870912),
("TinkeringMaterial", 1073741824), ("Gameboard", 2147483648),
}),
("PhysicsState", true, new (string, long)[]
{
("None", 0), ("Static", 1), ("Ethereal", 4), ("ReportCollision", 8), ("IgnoreCollision", 16),
("NoDraw", 32), ("Missle", 64), ("Pushable", 128), ("AlignPath", 256), ("PathClipped", 512),
("Gravity", 1024), ("LightingOn", 2048), ("ParticleEmitter", 4096), ("Hidden", 16384),
("ScriptedCollision", 32768), ("HasPhysicsBsp", 65536), ("Inelastic", 131072),
("HasDefaultAnim", 262144), ("HasDefaultScript", 524288), ("Cloaked", 1048576),
("ReportCollisionAsEnvironment", 2097152), ("EdgeSlide", 4194304), ("Sledding", 8388608),
("Frozen", 16777216),
}),
("PlayScript", false, new (string, long)[]
{
("Invalid", 0), ("Test1", 1), ("Test2", 2), ("Test3", 3), ("Launch", 4), ("Explode", 5),
("AttribUpRed", 6), ("AttribDownRed", 7), ("AttribUpOrange", 8), ("AttribDownOrange", 9),
("AttribUpYellow", 10), ("AttribDownYellow", 11), ("AttribUpGreen", 12), ("AttribDownGreen", 13),
("AttribUpBlue", 14), ("AttribDownBlue", 15), ("AttribUpPurple", 16), ("AttribDownPurple", 17),
("SkillUpRed", 18), ("SkillDownRed", 19), ("SkillUpOrange", 20), ("SkillDownOrange", 21),
("SkillUpYellow", 22), ("SkillDownYellow", 23), ("SkillUpGreen", 24), ("SkillDownGreen", 25),
("SkillUpBlue", 26), ("SkillDownBlue", 27), ("SkillUpPurple", 28), ("SkillDownPurple", 29),
("SkillDownBlack", 30), ("HealthUpRed", 31), ("HealthDownRed", 32), ("HealthUpBlue", 33),
("HealthDownBlue", 34), ("HealthUpYellow", 35), ("HealthDownYellow", 36), ("RegenUpRed", 37),
("RegenDownREd", 38), ("RegenUpBlue", 39), ("RegenDownBlue", 40), ("RegenUpYellow", 41),
("RegenDownYellow", 42), ("ShieldUpRed", 43), ("ShieldDownRed", 44), ("ShieldUpOrange", 45),
("ShieldDownOrange", 46), ("ShieldUpYellow", 47), ("ShieldDownYellow", 48), ("ShieldUpGreen", 49),
("ShieldDownGreen", 50), ("ShieldUpBlue", 51), ("ShieldDownBlue", 52), ("ShieldUpPurple", 53),
("ShieldDownPurple", 54), ("ShieldUpGrey", 55), ("ShieldDownGrey", 56), ("EnchantUpRed", 57),
("EnchantDownRed", 58), ("EnchantUpOrange", 59), ("EnchantDownOrange", 60), ("EnchantUpYellow", 61),
("EnchantDownYellow", 62), ("EnchantUpGreen", 63), ("EnchantDownGreen", 64), ("EnchantUpBlue", 65),
("EnchantDownBlue", 66), ("EnchantUpPurple", 67), ("EnchantDownPurple", 68), ("VitaeUpWhite", 69),
("VitaeDownBlack", 70), ("VisionUpWhite", 71), ("VisionDownBlack", 72), ("SwapHealth_Red_To_Yellow", 73),
("SwapHealth_Red_To_Blue", 74), ("SwapHealth_Yellow_To_Red", 75), ("SwapHealth_Yellow_To_Blue", 76),
("SwapHealth_Blue_To_Red", 77), ("SwapHealth_Blue_To_Yellow", 78), ("TransUpWhite", 79),
("TransDownBlack", 80), ("Fizzle", 81), ("PortalEntry", 82), ("PortalExit", 83), ("BreatheFlame", 84),
("BreatheFrost", 85), ("BreatheAcid", 86), ("BreatheLightning", 87), ("Create", 88), ("Destroy", 89),
("ProjectileCollision", 90), ("SplatterLowLeftBack", 91), ("SplatterLowLeftFront", 92),
("SplatterLowRightBack", 93), ("SplatterLowRightFront", 94), ("SplatterMidLeftBack", 95),
("SplatterMidLeftFront", 96), ("SplatterMidRightBack", 97), ("SplatterMidRightFront", 98),
("SplatterUpLeftBack", 99), ("SplatterUpLeftFront", 100), ("SplatterUpRightBack", 101),
("SplatterUpRightFront", 102), ("SparkLowLeftBack", 103), ("SparkLowLeftFront", 104),
("SparkLowRightBack", 105), ("SparkLowRightFront", 106), ("SparkMidLeftBack", 107),
("SparkMidLeftFront", 108), ("SparkMidRightBack", 109), ("SparkMidRightFront", 110),
("SparkUpLeftBack", 111), ("SparkUpLeftFront", 112), ("SparkUpRightBack", 113),
("SparkUpRightFront", 114), ("PortalStorm", 115), ("Hide", 116), ("UnHide", 117), ("Hidden", 118),
("DisappearDestroy", 119), ("SpecialState1", 120), ("SpecialState2", 121), ("SpecialState3", 122),
("SpecialState4", 123), ("SpecialState5", 124), ("SpecialState6", 125), ("SpecialState7", 126),
("SpecialState8", 127), ("SpecialState9", 128), ("SpecialState0", 129), ("SpecialStateRed", 130),
("SpecialStateOrange", 131), ("SpecialStateYellow", 132), ("SpecialStateGreen", 133),
("SpecialStateBlue", 134), ("SpecialStatePurple", 135), ("SpecialStateWhite", 136),
("SpecialStateBlack", 137), ("LevelUp", 138), ("EnchantUpGrey", 139), ("EnchantDownGrey", 140),
("WeddingBliss", 141), ("EnchantUpWhite", 142), ("EnchantDownWhite", 143), ("CampingMastery", 144),
("CampingIneptitude", 145), ("DispelLife", 146), ("DispelCreature", 147), ("DispelAll", 148),
("BunnySmite", 149), ("BaelZharonSmite", 150), ("WeddingSteele", 151), ("RestrictionEffectBlue", 152),
("RestrictionEffectGreen", 153), ("RestrictionEffectGold", 154), ("LayingofHands", 155),
("AugmentationUseAttribute", 156), ("AugmentationUseSkill", 157), ("AugmentationUseResistances", 158),
("AugmentationUseOther", 159), ("BlackMadness", 160), ("AetheriaLevelUp", 161),
("AetheriaSurgeDestruction", 162), ("AetheriaSurgeProtection", 163), ("AetheriaSurgeRegeneration", 164),
("AetheriaSurgeAffliction", 165), ("AetheriaSurgeFestering", 166), ("HealthDownVoid", 167),
("RegenDownVoid", 168), ("SkillDownVoid", 169), ("DirtyFightingHealDebuff", 170),
("DirtyFightingAttackDebuff", 171), ("DirtyFightingDefenseDebuff", 172),
("DirtyFightingDamageOverTime", 173),
}),
("RadarBehavior", false, new (string, long)[]
{
("Undefined", 0), ("ShowNever", 1), ("ShowMovement", 2), ("ShowAttacking", 3), ("ShowAlways", 4),
}),
("RadarColor", false, new (string, long)[]
{
("Default", 0), ("Blue", 1), ("Gold", 2), ("White", 3), ("Purple", 4), ("Red", 5), ("Pink", 6),
("Green", 7), ("Yellow", 8), ("Cyan", 9), ("BrightGreen", 16), ("Admin", 9), ("Advocate", 6),
("Creature", 2), ("LifeStone", 1), ("NPC", 8), ("PlayerKiller", 5), ("Portal", 4), ("Sentinel", 9),
("Vendor", 8), ("Fellowship", 16), ("FellowshipLeader", 16), ("PKLite", 6),
}),
("SkillTrainingType", false, new (string, long)[]
{
("Unusable", 0), ("Untrained", 1), ("Trained", 2), ("Specialized", 3),
}),
("SpellCategory", false, new (string, long)[]
{
("Undef", 0), ("StrengthRaising", 1), ("StrengthLowering", 2), ("EnduranceRaising", 3),
("EnduranceLowering", 4), ("QuicknessRaising", 5), ("QuicknessLowering", 6), ("CoordinationRaising", 7),
("CoordinationLowering", 8), ("FocusRaising", 9), ("FocusLowering", 10), ("SelfRaising", 11),
("SelfLowering", 12), ("FocusConcentration", 13), ("FocusDisruption", 14), ("FocusBrilliance", 15),
("FocusDullness", 16), ("AxeRaising", 17), ("AxeLowering", 18), ("BowRaising", 19), ("BowLowering", 20),
("CrossbowRaising", 21), ("CrossbowLowering", 22), ("DaggerRaising", 23), ("DaggerLowering", 24),
("MaceRaising", 25), ("MaceLowering", 26), ("SpearRaising", 27), ("SpearLowering", 28),
("StaffRaising", 29), ("StaffLowering", 30), ("SwordRaising", 31), ("SwordLowering", 32),
("ThrownWeaponsRaising", 33), ("ThrownWeaponsLowering", 34), ("UnarmedCombatRaising", 35),
("UnarmedCombatLowering", 36), ("MeleeDefenseRaising", 37), ("MeleeDefenseLowering", 38),
("MissileDefenseRaising", 39), ("MissileDefenseLowering", 40), ("MagicDefenseRaising", 41),
("MagicDefenseLowering", 42), ("CreatureEnchantmentRaising", 43), ("CreatureEnchantmentLowering", 44),
("ItemEnchantmentRaising", 45), ("ItemEnchantmentLowering", 46), ("LifeMagicRaising", 47),
("LifeMagicLowering", 48), ("WarMagicRaising", 49), ("WarMagicLowering", 50),
("ManaConversionRaising", 51), ("ManaConversionLowering", 52), ("ArcaneLoreRaising", 53),
("ArcaneLoreLowering", 54), ("AppraiseArmorRaising", 55), ("AppraiseArmorLowering", 56),
("AppraiseItemRaising", 57), ("AppraiseItemLowering", 58), ("AppraiseMagicItemRaising", 59),
("AppraiseMagicItemLowering", 60), ("AppraiseWeaponRaising", 61), ("AppraiseWeaponLowering", 62),
("AssessMonsterRaising", 63), ("AssessMonsterLowering", 64), ("DeceptionRaising", 65),
("DeceptionLowering", 66), ("HealingRaising", 67), ("HealingLowering", 68), ("JumpRaising", 69),
("JumpLowering", 70), ("LeadershipRaising", 71), ("LeadershipLowering", 72), ("LockpickRaising", 73),
("LockpickLowering", 74), ("LoyaltyRaising", 75), ("LoyaltyLowering", 76), ("RunRaising", 77),
("RunLowering", 78), ("HealthRaising", 79), ("HealthLowering", 80), ("StaminaRaising", 81),
("StaminaLowering", 82), ("ManaRaising", 83), ("ManaLowering", 84), ("ManaRemedy", 85),
("ManaMalediction", 86), ("HealthTransfertocaster", 87), ("HealthTransferfromcaster", 88),
("StaminaTransfertocaster", 89), ("StaminaTransferfromcaster", 90), ("ManaTransfertocaster", 91),
("ManaTransferfromcaster", 92), ("HealthAccelerating", 93), ("HealthDecelerating", 94),
("StaminaAccelerating", 95), ("StaminaDecelerating", 96), ("ManaAccelerating", 97),
("ManaDecelerating", 98), ("VitaeRaising", 99), ("VitaeLowering", 100), ("AcidProtection", 101),
("AcidVulnerability", 102), ("BludgeonProtection", 103), ("BludgeonVulnerability", 104),
("ColdProtection", 105), ("ColdVulnerability", 106), ("ElectricProtection", 107),
("ElectricVulnerability", 108), ("FireProtection", 109), ("FireVulnerability", 110),
("PierceProtection", 111), ("PierceVulnerability", 112), ("SlashProtection", 113),
("SlashVulnerability", 114), ("ArmorRaising", 115), ("ArmorLowering", 116), ("AcidMissile", 117),
("BludgeoningMissile", 118), ("ColdMissile", 119), ("ElectricMissile", 120), ("FireMissile", 121),
("PiercingMissile", 122), ("SlashingMissile", 123), ("AcidSeeker", 124), ("BludgeoningSeeker", 125),
("ColdSeeker", 126), ("ElectricSeeker", 127), ("FireSeeker", 128), ("PiercingSeeker", 129),
("SlashingSeeker", 130), ("AcidBurst", 131), ("BludgeoningBurst", 132), ("ColdBurst", 133),
("ElectricBurst", 134), ("FireBurst", 135), ("PiercingBurst", 136), ("SlashingBurst", 137),
("AcidBlast", 138), ("BludgeoningBlast", 139), ("ColdBlast", 140), ("ElectricBlast", 141),
("FireBlast", 142), ("PiercingBlast", 143), ("SlashingBlast", 144), ("AcidScatter", 145),
("BludgeoningScatter", 146), ("ColdScatter", 147), ("ElectricScatter", 148), ("FireScatter", 149),
("PiercingScatter", 150), ("SlashingScatter", 151), ("AttackModRaising", 152),
("AttackModLowering", 153), ("DamageRaising", 154), ("DamageLowering", 155), ("DefenseModRaising", 156),
("DefenseModLowering", 157), ("WeaponTimeRaising", 158), ("WeaponTimeLowering", 159),
("ArmorValueRaising", 160), ("ArmorValueLowering", 161), ("AcidResistanceRaising", 162),
("AcidResistanceLowering", 163), ("BludgeonResistanceRaising", 164), ("BludgeonResistanceLowering", 165),
("ColdResistanceRaising", 166), ("ColdResistanceLowering", 167), ("ElectricResistanceRaising", 168),
("ElectricResistanceLowering", 169), ("FireResistanceRaising", 170), ("FireResistanceLowering", 171),
("PierceResistanceRaising", 172), ("PierceResistanceLowering", 173), ("SlashResistanceRaising", 174),
("SlashResistanceLowering", 175), ("BludgeoningResistanceRaising", 176),
("BludgeoningResistanceLowering", 177), ("SlashingResistanceRaising", 178),
("SlashingResistanceLowering", 179), ("PiercingResistanceRaising", 180),
("PiercingResistanceLowering", 181), ("ElectricalResistanceRaising", 182),
("ElectricalResistanceLowering", 183), ("FrostResistanceRaising", 184), ("FrostResistanceLowering", 185),
("FlameResistanceRaising", 186), ("FlameResistanceLowering", 187), ("AcidicResistanceRaising", 188),
("AcidicResistanceLowering", 189), ("ArmorLevelRaising", 190), ("ArmorLevelLowering", 191),
("LockpickResistanceRaising", 192), ("LockpickResistanceLowering", 193),
("ManaConversionModLowering", 194), ("ManaConversionModRaising", 195), ("VisionRaising", 196),
("VisionLowering", 197), ("TransparencyRaising", 198), ("TransparencyLowering", 199), ("PortalTie", 200),
("PortalRecall", 201), ("PortalCreation", 202), ("PortalItemCreation", 203), ("Vitae", 204),
("AssessPersonRaising", 205), ("AssessPersonLowering", 206), ("AcidVolley", 207),
("BludgeoningVolley", 208), ("FrostVolley", 209), ("LightningVolley", 210), ("FlameVolley", 211),
("ForceVolley", 212), ("BladeVolley", 213), ("PortalSending", 214), ("LifestoneSending", 215),
("CookingRaising", 216), ("CookingLowering", 217), ("FletchingRaising", 218), ("FletchingLowering", 219),
("AlchemyLowering", 220), ("AlchemyRaising", 221), ("AcidRing", 222), ("BludgeoningRing", 223),
("ColdRing", 224), ("ElectricRing", 225), ("FireRing", 226), ("PiercingRing", 227),
("SlashingRing", 228), ("AcidWall", 229), ("BludgeoningWall", 230), ("ColdWall", 231),
("ElectricWall", 232), ("FireWall", 233), ("PiercingWall", 234), ("SlashingWall", 235),
("AcidStrike", 236), ("BludgeoningStrike", 237), ("ColdStrike", 238), ("ElectricStrike", 239),
("FireStrike", 240), ("PiercingStrike", 241), ("SlashingStrike", 242), ("AcidStreak", 243),
("BludgeoningStreak", 244), ("ColdStreak", 245), ("ElectricStreak", 246), ("FireStreak", 247),
("PiercingStreak", 248), ("SlashingStreak", 249), ("Dispel", 250), ("CreatureMysticRaising", 251),
("CreatureMysticLowering", 252), ("ItemMysticRaising", 253), ("ItemMysticLowering", 254),
("WarMysticRaising", 255), ("WarMysticLowering", 256), ("HealthRestoring", 257),
("HealthDepleting", 258), ("ManaRestoring", 259), ("ManaDepleting", 260), ("StrengthIncrease", 261),
("StrengthDecrease", 262), ("EnduranceIncrease", 263), ("EnduranceDecrease", 264),
("QuicknessIncrease", 265), ("QuicknessDecrease", 266), ("CoordinationIncrease", 267),
("CoordinationDecrease", 268), ("FocusIncrease", 269), ("FocusDecrease", 270), ("SelfIncrease", 271),
("SelfDecrease", 272), ("GreatVitalityRaising", 273), ("PoorVitalityLowering", 274),
("GreatVigorRaising", 275), ("PoorVigorLowering", 276), ("GreaterIntellectRaising", 277),
("LessorIntellectLowering", 278), ("LifeGiverRaising", 279), ("LifeTakerLowering", 280),
("StaminaGiverRaising", 281), ("StaminaTakerLowering", 282), ("ManaGiverRaising", 283),
("ManaTakerLowering", 284), ("AcidWardProtection", 285), ("AcidWardVulnerability", 286),
("FireWardProtection", 287), ("FireWardVulnerability", 288), ("ColdWardProtection", 289),
("ColdWardVulnerability", 290), ("ElectricWardProtection", 291), ("ElectricWardVulnerability", 292),
("LeadershipObedienceRaising", 293), ("LeadershipObedienceLowering", 294),
("MeleeDefenseShelterRaising", 295), ("MeleeDefenseShelterLowering", 296),
("MissileDefenseShelterRaising", 297), ("MissileDefenseShelterLowering", 298),
("MagicDefenseShelterRaising", 299), ("MagicDefenseShelterLowering", 300), ("HuntersAcumenRaising", 301),
("HuntersAcumenLowering", 302), ("StillWaterRaising", 303), ("StillWaterLowering", 304),
("StrengthofEarthRaising", 305), ("StrengthofEarthLowering", 306), ("TorrentRaising", 307),
("TorrentLowering", 308), ("GrowthRaising", 309), ("GrowthLowering", 310), ("CascadeAxeRaising", 311),
("CascadeAxeLowering", 312), ("CascadeDaggerRaising", 313), ("CascadeDaggerLowering", 314),
("CascadeMaceRaising", 315), ("CascadeMaceLowering", 316), ("CascadeSpearRaising", 317),
("CascadeSpearLowering", 318), ("CascadeStaffRaising", 319), ("CascadeStaffLowering", 320),
("StoneCliffsRaising", 321), ("StoneCliffsLowering", 322), ("MaxDamageRaising", 323),
("MaxDamageLowering", 324), ("BowDamageRaising", 325), ("BowDamageLowering", 326),
("BowRangeRaising", 327), ("BowRangeLowering", 328), ("ExtraDefenseModRaising", 329),
("ExtraDefenseModLowering", 330), ("ExtraBowSkillRaising", 331), ("ExtraBowSkillLowering", 332),
("ExtraAlchemySkillRaising", 333), ("ExtraAlchemySkillLowering", 334),
("ExtraArcaneLoreSkillRaising", 335), ("ExtraArcaneLoreSkillLowering", 336),
("ExtraAppraiseArmorSkillRaising", 337), ("ExtraAppraiseArmorSkillLowering", 338),
("ExtraCookingSkillRaising", 339), ("ExtraCookingSkillLowering", 340),
("ExtraCrossbowSkillRaising", 341), ("ExtraCrossbowSkillLowering", 342),
("ExtraDeceptionSkillRaising", 343), ("ExtraDeceptionSkillLowering", 344),
("ExtraLoyaltySkillRaising", 345), ("ExtraLoyaltySkillLowering", 346),
("ExtraFletchingSkillRaising", 347), ("ExtraFletchingSkillLowering", 348),
("ExtraHealingSkillRaising", 349), ("ExtraHealingSkillLowering", 350),
("ExtraMeleeDefenseSkillRaising", 351), ("ExtraMeleeDefenseSkillLowering", 352),
("ExtraAppraiseItemSkillRaising", 353), ("ExtraAppraiseItemSkillLowering", 354),
("ExtraJumpingSkillRaising", 355), ("ExtraJumpingSkillLowering", 356),
("ExtraLifeMagicSkillRaising", 357), ("ExtraLifeMagicSkillLowering", 358),
("ExtraLockpickSkillRaising", 359), ("ExtraLockpickSkillLowering", 360),
("ExtraAppraiseMagicItemSkillRaising", 361), ("ExtraAppraiseMagicItemSkillLowering", 362),
("ExtraManaConversionSkillRaising", 363), ("ExtraManaConversionSkillLowering", 364),
("ExtraAssessCreatureSkillRaising", 365), ("ExtraAssessCreatureSkillLowering", 366),
("ExtraAssessPersonSkillRaising", 367), ("ExtraAssessPersonSkillLowering", 368),
("ExtraRunSkillRaising", 369), ("ExtraRunSkillLowering", 370), ("ExtraSwordSkillRaising", 371),
("ExtraSwordSkillLowering", 372), ("ExtraThrownWeaponsSkillRaising", 373),
("ExtraThrownWeaponsSkillLowering", 374), ("ExtraUnarmedCombatSkillRaising", 375),
("ExtraUnarmedCombatSkillLowering", 376), ("ExtraAppraiseWeaponSkillRaising", 377),
("ExtraAppraiseWeaponSkillLowering", 378), ("ArmorIncrease", 379), ("ArmorDecrease", 380),
("ExtraAcidResistanceRaising", 381), ("ExtraAcidResistanceLowering", 382),
("ExtraBludgeonResistanceRaising", 383), ("ExtraBludgeonResistanceLowering", 384),
("ExtraFireResistanceRaising", 385), ("ExtraFireResistanceLowering", 386),
("ExtraColdResistanceRaising", 387), ("ExtraColdResistanceLowering", 388),
("ExtraAttackModRaising", 389), ("ExtraAttackModLowering", 390), ("ExtraArmorValueRaising", 391),
("ExtraArmorValueLowering", 392), ("ExtraPierceResistanceRaising", 393),
("ExtraPierceResistanceLowering", 394), ("ExtraSlashResistanceRaising", 395),
("ExtraSlashResistanceLowering", 396), ("ExtraElectricResistanceRaising", 397),
("ExtraElectricResistanceLowering", 398), ("ExtraWeaponTimeRaising", 399),
("ExtraWeaponTimeLowering", 400), ("BludgeonWardProtection", 401), ("BludgeonWardVulnerability", 402),
("SlashWardProtection", 403), ("SlashWardVulnerability", 404), ("PierceWardProtection", 405),
("PierceWardVulnerability", 406), ("StaminaRestoring", 407), ("StaminaDepleting", 408),
("Fireworks", 409), ("HealthDivide", 410), ("StaminaDivide", 411), ("ManaDivide", 412),
("CoordinationIncrease2", 413), ("StrengthIncrease2", 414), ("FocusIncrease2", 415),
("EnduranceIncrease2", 416), ("SelfIncrease2", 417), ("MeleeDefenseMultiply", 418),
("MissileDefenseMultiply", 419), ("MagicDefenseMultiply", 420), ("AttributesDecrease", 421),
("LifeGiverRaising2", 422), ("ItemEnchantmentRaising2", 423), ("SkillsDecrease", 424),
("ExtraManaConversionBonus", 425), ("WarMysticRaising2", 426), ("WarMysticLowering2", 427),
("MagicDefenseShelterRaising2", 428), ("ExtraLifeMagicSkillRaising2", 429),
("CreatureMysticRaising2", 430), ("ItemMysticRaising2", 431), ("ManaRaising2", 432),
("SelfRaising2", 433), ("CreatureEnchantmentRaising2", 434), ("SalvagingRaising", 435),
("ExtraSalvagingRaising", 436), ("ExtraSalvagingRaising2", 437), ("CascadeAxeRaising2", 438),
("ExtraBowSkillRaising2", 439), ("ExtraThrownWeaponsSkillRaising2", 440),
("ExtraCrossbowSkillRaising2", 441), ("CascadeDaggerRaising2", 442), ("CascadeMaceRaising2", 443),
("ExtraUnarmedCombatSkillRaising2", 444), ("CascadeSpearRaising2", 445), ("CascadeStaffRaising2", 446),
("ExtraSwordSkillRaising2", 447), ("AcidProtectionRare", 448), ("AcidResistanceRaisingRare", 449),
("AlchemyRaisingRare", 450), ("AppraisalResistanceLoweringRare", 451), ("AppraiseArmorRaisingRare", 452),
("AppraiseItemRaisingRare", 453), ("AppraiseMagicItemRaisingRare", 454),
("AppraiseWeaponRaisingRare", 455), ("ArcaneLoreRaisingRare", 456), ("ArmorRaisingRare", 457),
("ArmorValueRaisingRare", 458), ("AssessMonsterRaisingRare", 459), ("AssessPersonRaisingRare", 460),
("AttackModRaisingRare", 461), ("AxeRaisingRare", 462), ("BludgeonProtectionRare", 463),
("BludgeonResistanceRaisingRare", 464), ("BowRaisingRare", 465), ("ColdProtectionRare", 466),
("ColdResistanceRaisingRare", 467), ("CookingRaisingRare", 468), ("CoordinationRaisingRare", 469),
("CreatureEnchantmentRaisingRare", 470), ("CrossbowRaisingRare", 471), ("DaggerRaisingRare", 472),
("DamageRaisingRare", 473), ("DeceptionRaisingRare", 474), ("DefenseModRaisingRare", 475),
("ElectricProtectionRare", 476), ("ElectricResistanceRaisingRare", 477), ("EnduranceRaisingRare", 478),
("FireProtectionRare", 479), ("FireResistanceRaisingRare", 480), ("FletchingRaisingRare", 481),
("FocusRaisingRare", 482), ("HealingRaisingRare", 483), ("HealthAcceleratingRare", 484),
("ItemEnchantmentRaisingRare", 485), ("JumpRaisingRare", 486), ("LeadershipRaisingRare", 487),
("LifeMagicRaisingRare", 488), ("LockpickRaisingRare", 489), ("LoyaltyRaisingRare", 490),
("MaceRaisingRare", 491), ("MagicDefenseRaisingRare", 492), ("ManaAcceleratingRare", 493),
("ManaConversionRaisingRare", 494), ("MeleeDefenseRaisingRare", 495), ("MissileDefenseRaisingRare", 496),
("PierceProtectionRare", 497), ("PierceResistanceRaisingRare", 498), ("QuicknessRaisingRare", 499),
("RunRaisingRare", 500), ("SelfRaisingRare", 501), ("SlashProtectionRare", 502),
("SlashResistanceRaisingRare", 503), ("SpearRaisingRare", 504), ("StaffRaisingRare", 505),
("StaminaAcceleratingRare", 506), ("StrengthRaisingRare", 507), ("SwordRaisingRare", 508),
("ThrownWeaponsRaisingRare", 509), ("UnarmedCombatRaisingRare", 510), ("WarMagicRaisingRare", 511),
("WeaponTimeRaisingRare", 512), ("ArmorIncreaseInkyArmor", 513), ("MagicDefenseShelterRaisingFiun", 514),
("ExtraRunSkillRaisingFiun", 515), ("ExtraManaConversionSkillRaisingFiun", 516),
("AttributesIncreaseCantrip1", 517), ("ExtraMeleeDefenseSkillRaising2", 518),
("ACTDPurchaseRewardSpell", 519), ("ACTDPurchaseRewardSpellHealth", 520),
("SaltAshAttackModRaising", 521), ("QuicknessIncrease2", 522), ("ExtraAlchemySkillRaising2", 523),
("ExtraCookingSkillRaising2", 524), ("ExtraFletchingSkillRaising2", 525),
("ExtraLockpickSkillRaising2", 526), ("MucorManaWell", 527), ("StaminaRestoring2", 528),
("AllegianceRaising", 529), ("HealthDoT", 530), ("HealthDoTSecondary", 531), ("HealthDoTTertiary", 532),
("HealthHoT", 533), ("HealthHoTSecondary", 534), ("HealthHoTTertiary", 535),
("HealthDivideSecondary", 536), ("HealthDivideTertiary", 537), ("SetSwordRaising", 538),
("SetAxeRaising", 539), ("SetDaggerRaising", 540), ("SetMaceRaising", 541), ("SetSpearRaising", 542),
("SetStaffRaising", 543), ("SetUnarmedRaising", 544), ("SetBowRaising", 545),
("SetCrossbowRaising", 546), ("SetThrownRaising", 547), ("SetItemEnchantmentRaising", 548),
("SetCreatureEnchantmentRaising", 549), ("SetWarMagicRaising", 550), ("SetLifeMagicRaising", 551),
("SetMeleeDefenseRaising", 552), ("SetMissileDefenseRaising", 553), ("SetMagicDefenseRaising", 554),
("SetStaminaAccelerating", 555), ("SetCookingRaising", 556), ("SetFletchingRaising", 557),
("SetLockpickRaising", 558), ("SetAlchemyRaising", 559), ("SetSalvagingRaising", 560),
("SetArmorExpertiseRaising", 561), ("SetWeaponExpertiseRaising", 562), ("SetItemTinkeringRaising", 563),
("SetMagicItemExpertiseRaising", 564), ("SetLoyaltyRaising", 565), ("SetStrengthRaising", 566),
("SetEnduranceRaising", 567), ("SetCoordinationRaising", 568), ("SetQuicknessRaising", 569),
("SetFocusRaising", 570), ("SetWillpowerRaising", 571), ("SetHealthRaising", 572),
("SetStaminaRaising", 573), ("SetManaRaising", 574), ("SetSprintRaising", 575),
("SetJumpingRaising", 576), ("SetSlashResistanceRaising", 577), ("SetBludgeonResistanceRaising", 578),
("SetPierceResistanceRaising", 579), ("SetFlameResistanceRaising", 580),
("SetAcidResistanceRaising", 581), ("SetFrostResistanceRaising", 582),
("SetLightningResistanceRaising", 583), ("CraftingLockPickRaising", 584),
("CraftingFletchingRaising", 585), ("CraftingCookingRaising", 586), ("CraftingAlchemyRaising", 587),
("CraftingArmorTinkeringRaising", 588), ("CraftingWeaponTinkeringRaising", 589),
("CraftingMagicTinkeringRaising", 590), ("CraftingItemTinkeringRaising", 591),
("SkillPercentAlchemyRaising", 592), ("TwoHandedRaising", 593), ("TwoHandedLowering", 594),
("ExtraTwoHandedSkillRaising", 595), ("ExtraTwoHandedSkillLowering", 596),
("ExtraTwoHandedSkillRaising2", 597), ("TwoHandedRaisingRare", 598), ("SetTwoHandedRaising", 599),
("GearCraftRaising", 600), ("GearCraftLowering", 601), ("ExtraGearCraftSkillRaising", 602),
("ExtraGearCraftSkillLowering", 603), ("ExtraGearCraftSkillRaising2", 604),
("GearCraftRaisingRare", 605), ("SetGearCraftRaising", 606), ("LoyaltyManaRaising", 607),
("LoyaltyStaminaRaising", 608), ("LeadershipHealthRaising", 609), ("TrinketDamageRaising", 610),
("TrinketDamageLowering", 611), ("TrinketHealthRaising", 612), ("TrinketStaminaRaising", 613),
("TrinketManaRaising", 614), ("TrinketXPRaising", 615), ("DeceptionArcaneLoreRaising", 616),
("HealOverTimeRaising", 617), ("DamageOverTimeRaising", 618), ("HealingResistRatingRaising", 619),
("AetheriaDamageRatingRaising", 620), ("AetheriaDamageReductionRaising", 621),
("AetheriaHealthRaising", 623), ("AetheriaStaminaRaising", 624), ("AetheriaManaRaising", 625),
("AetheriaCriticalDamageRaising", 626), ("AetheriaHealingAmplificationRaising", 627),
("AetheriaProcDamageRatingRaising", 628), ("AetheriaProcDamageReductionRaising", 629),
("AetheriaProcHealthOverTimeRaising", 630), ("AetheriaProcDamageOverTimeRaising", 631),
("AetheriaProcHealingReductionRaising", 632), ("RareDamageRatingRaising", 633),
("RareDamageReductionRatingRaising", 634), ("AetheriaEnduranceRaising", 635),
("NetherDamageOverTimeRaising", 636), ("NetherDamageOverTimeRaising2", 637),
("NetherDamageOverTimeRaising3", 638), ("NetherStreak", 639), ("NetherMissile", 640),
("NetherRing", 641), ("NetherDamageRatingLowering", 642), ("NetherDamageHealingReductionRaising", 643),
("VoidMagicLowering", 644), ("VoidMagicRaising", 645), ("VoidMysticRaising", 646),
("SetVoidMagicRaising", 647), ("VoidMagicRaisingRare", 648), ("VoidMysticRaising2", 649),
("LuminanceDamageRatingRaising", 650), ("LuminanceDamageReductionRaising", 651),
("LuminanceHealthRaising", 652), ("AetheriaCriticalReductionRaising", 653),
("ExtraMissileDefenseSkillRaising", 654), ("ExtraMissileDefenseSkillLowering", 655),
("ExtraMissileDefenseSkillRaising2", 656), ("AetheriaHealthResistanceRaising", 657),
("AetheriaDotResistanceRaising", 658), ("CloakSkillRaising", 659), ("CloakAllSkillRaising", 660),
("CloakMagicDefenseLowering", 661), ("CloakMeleeDefenseLowering", 662),
("CloakMissileDefenseLowering", 663), ("DirtyFightingLowering", 664), ("DirtyFightingRaising", 665),
("ExtraDirtyFightingRaising", 666), ("DualWieldLowering", 667), ("DualWieldRaising", 668),
("ExtraDualWieldRaising", 669), ("RecklessnessLowering", 670), ("RecklessnessRaising", 671),
("ExtraRecklessnessRaising", 672), ("ShieldLowering", 673), ("ShieldRaising", 674),
("ExtraShieldRaising", 675), ("SneakAttackLowering", 676), ("SneakAttackRaising", 677),
("ExtraSneakAttackRaising", 678), ("RareDirtyFightingRaising", 679), ("RareDualWieldRaising", 680),
("RareRecklessnessRaising", 681), ("RareShieldRaising", 682), ("RareSneakAttackRaising", 683),
("DFAttackSkillDebuff", 684), ("DFBleedDamage", 685), ("DFDefenseSkillDebuff", 686),
("DFHealingDebuff", 687), ("SetDirtyFightingRaising", 688), ("SetDualWieldRaising", 689),
("SetRecklessnessRaising", 690), ("SetShieldRaising", 691), ("SetSneakAttackRaising", 692),
("LifeGiverMhoire", 693), ("RareDamageRatingRaising2", 694), ("SpellDamageRaising", 695),
("SummoningRaising", 696), ("SummoningLowering", 697), ("ExtraSummoningSkillRaising", 698),
("SetSummoningRaising", 699), ("ParagonEnduranceRaising", 704), ("ParagonManaRaising", 705),
("ParagonStaminaRaising", 706), ("ParagonDirtyFightingRaising", 707), ("ParagonDualWieldRaising", 708),
("ParagonRecklessnessRaising", 709), ("ParagonSneakAttackRaising", 710),
("ParagonDamageRatingRaising", 711), ("ParagonDamageReductionRatingRaising", 712),
("ParagonCriticalDamageRatingRaising", 713), ("ParagonCriticalDamageReductionRatingRaising", 714),
("ParagonAxeRaising", 715), ("ParagonDaggerRaising", 716), ("ParagonSwordRaising", 717),
("ParagonWarMagicRaising", 718), ("ParagonLifeMagicRaising", 719), ("ParagonVoidMagicRaising", 720),
("ParagonBowRaising", 721), ("ParagonStrengthRaising", 722), ("ParagonCoordinationRaising", 723),
("ParagonQuicknessRaising", 724), ("ParagonFocusRaising", 725), ("ParagonWillpowerRaising", 726),
("ParagonTwoHandedRaising", 727), ("GauntletDamageReductionRatingRaising", 728),
("GauntletDamageRatingRaising", 729), ("GauntletHealingRatingRaising", 730),
("GauntletVitalityRaising", 731), ("GauntletCriticalDamageRatingRaising", 732),
("GauntletCriticalDamageReductionRatingRaising", 733),
}),
("SpellFlags", true, new (string, long)[]
{
("Resistable", 1), ("PKSensitive", 2), ("Beneficial", 4), ("SelfTargeted", 8), ("Reversed", 16),
("NotIndoor", 32), ("NotOutdoor", 64), ("NotResearchable", 128), ("Projectile", 256),
("CreatureSpell", 512), ("ExcludedFromItemDescriptions", 1024), ("IgnoresManaConversion", 2048),
("NonTrackingProjectile", 4096), ("FellowshipSpell", 8192), ("FastCast", 16384),
("IndoorLongRange", 32768), ("DamageOverTime", 65536), ("UNKNOWN", 131072),
}),
("SpellType", false, new (string, long)[]
{
("Undef", 0), ("Enchantment", 1), ("Projectile", 2), ("Boost", 3), ("Transfer", 4), ("PortalLink", 5),
("PortalRecall", 6), ("PortalSummon", 7), ("PortalSending", 8), ("Dispel", 9), ("LifeProjectile", 10),
("FellowBoost", 11), ("FellowEnchantment", 12), ("FellowPortalSending", 13), ("FellowDispel", 14),
("EnchantmentProjectile", 15),
}),
("TradeSide", false, new (string, long)[]
{
("Self", 1), ("Partner", 2),
}),
("UsableType", true, new (string, long)[]
{
("SourceUnusable", 1), ("SourceSelf", 2), ("SourceWielded", 4), ("SourceContained", 8),
("SourceViewed", 16), ("SourceRemote", 32), ("SourceNoApproach", 64), ("SourceObjectSelf", 128),
("TargetUnusable", 65536), ("TargetSelf", 131072), ("TargetWielded", 262144),
("TargetContained", 524288), ("TargetViewed", 1048576), ("TargetRemote", 2097152),
("TargetNoApproach", 4194304), ("TargetObjectSelf", 8388608),
}),
("Vital", false, new (string, long)[]
{
("Undef", 0), ("MaxHealth", 1), ("Health", 2), ("MaxStamina", 3), ("Stamina", 4), ("MaxMana", 5),
("Mana", 6),
}),
("WeenieError", false, new (string, long)[]
{
("None", 0), ("NoMem", 1), ("BadParam", 2), ("DivZero", 3), ("SegV", 4), ("Unimplemented", 5),
("UnknownMessageType", 6), ("NoAnimationTable", 7), ("NoPhysicsObject", 8), ("NoBookieObject", 9),
("NoWslObject", 10), ("NoMotionInterpreter", 11), ("UnhandledSwitch", 12),
("DefaultConstructorCalled", 13), ("InvalidCombatManeuver", 14), ("BadCast", 15), ("MissingQuality", 16),
("MissingDatabaseObject", 18), ("NoCallbackSet", 19), ("CorruptQuality", 20), ("BadContext", 21),
("NoEphseqManager", 22), ("BadMovementEvent", 23), ("CannotCreateNewObject", 24),
("NoControllerObject", 25), ("CannotSendEvent", 26), ("PhysicsCantTransition", 27),
("PhysicsMaxDistanceExceeded", 28), ("YoureTooBusy", 29), ("CannotSendMessage", 31),
("IllegalInventoryTransaction", 32), ("ExternalWeenieObject", 33), ("InternalWeenieObject", 34),
("MotionFailure", 35), ("YouCantJumpWhileInTheAir", 36), ("InqCylSphereFailure", 37),
("ThatIsNotAValidCommand", 38), ("CarryingItem", 39), ("Frozen", 40), ("Stuck", 41),
("YouAreTooEncumbered", 42), ("BadContain", 44), ("BadParent", 45), ("BadDrop", 46), ("BadRelease", 47),
("MsgBadMsg", 48), ("MsgUnpackFailed", 49), ("MsgNoMsg", 50), ("MsgUnderflow", 51), ("MsgOverflow", 52),
("MsgCallbackFailed", 53), ("ActionCancelled", 54), ("ObjectGone", 55), ("NoObject", 56),
("CantGetThere", 57), ("Dead", 58), ("ILeftTheWorld", 59), ("ITeleported", 60), ("YouChargedTooFar", 61),
("YouAreTooTiredToDoThat", 62), ("CantCrouchInCombat", 63), ("CantSitInCombat", 64),
("CantLieDownInCombat", 65), ("CantChatEmoteInCombat", 66), ("NoMtableData", 67),
("CantChatEmoteNotStanding", 68), ("TooManyActions", 69), ("Hidden", 70), ("GeneralMovementFailure", 71),
("YouCantJumpFromThisPosition", 72), ("CantJumpLoadedDown", 73), ("YouKilledYourself", 74),
("MsgResponseFailure", 75), ("ObjectIsStatic", 76), ("InvalidPkStatus", 77), ("InvalidXpAmount", 1001),
("InvalidPpCalculation", 1002), ("InvalidCpCalculation", 1003), ("UnhandledStatAnswer", 1004),
("HeartAttack", 1005), ("TheContainerIsClosed", 1006), ("InvalidInventoryLocation", 1008),
("ChangeCombatModeFailure", 1009), ("FullInventoryLocation", 1010),
("ConflictingInventoryLocation", 1011), ("ItemNotPending", 1012), ("BeWieldedFailure", 1013),
("BeDroppedFailure", 1014), ("YouAreTooFatiguedToAttack", 1015), ("YouAreOutOfAmmunition", 1016),
("YourAttackMisfired", 1017), ("YouveAttemptedAnImpossibleSpellPath", 1018),
("MagicIncompleteAnimList", 1019), ("MagicInvalidSpellType", 1020),
("MagicInqPositionAndVelocityFailure", 1021), ("YouDontKnowThatSpell", 1022),
("IncorrectTargetType", 1023), ("YouDontHaveAllTheComponents", 1024),
("YouDontHaveEnoughManaToCast", 1025), ("YourSpellFizzled", 1026), ("YourSpellTargetIsMissing", 1027),
("YourProjectileSpellMislaunched", 1028), ("MagicSpellbookAddSpellFailure", 1029),
("MagicTargetOutOfRange", 1030), ("YourSpellCannotBeCastOutside", 1031),
("YourSpellCannotBeCastInside", 1032), ("MagicGeneralFailure", 1033),
("YouAreUnpreparedToCastASpell", 1034), ("YouveAlreadySwornAllegiance", 1035),
("CantSwearAllegianceInsufficientXp", 1036), ("AllegianceIgnoringRequests", 1037),
("AllegianceSquelched", 1038), ("AllegianceMaxDistanceExceeded", 1039), ("AllegianceIllegalLevel", 1040),
("AllegianceBadCreation", 1041), ("AllegiancePatronBusy", 1042), ("YouAreNotInAllegiance", 1044),
("AllegianceRemoveHierarchyFailure", 1045), ("FellowshipIgnoringRequests", 1047),
("FellowshipSquelched", 1048), ("FellowshipMaxDistanceExceeded", 1049), ("FellowshipMember", 1050),
("FellowshipIllegalLevel", 1051), ("FellowshipRecruitBusy", 1052), ("YouMustBeLeaderOfFellowship", 1053),
("YourFellowshipIsFull", 1054), ("FellowshipNameIsNotPermitted", 1055), ("LevelTooLow", 1056),
("LevelTooHigh", 1057), ("ThatChannelDoesntExist", 1058), ("YouCantUseThatChannel", 1059),
("YouAreAlreadyOnThatChannel", 1060), ("YouAreNotOnThatChannel", 1061), ("AttunedItem", 1062),
("YouCannotMergeDifferentStacks", 1063), ("YouCannotMergeEnchantedItems", 1064),
("YouMustControlAtLeastOneStack", 1065), ("CurrentlyAttacking", 1066), ("MissileAttackNotOk", 1067),
("TargetNotAcquired", 1068), ("ImpossibleShot", 1069), ("BadWeaponSkill", 1070),
("UnwieldFailure", 1071), ("LaunchFailure", 1072), ("ReloadFailure", 1073),
("UnableToMakeCraftReq", 1074), ("CraftAnimationFailed", 1075),
("YouCantCraftWithThatNumberOfItems", 1076), ("CraftGeneralErrorUiMsg", 1077),
("CraftGeneralErrorNoUiMsg", 1078), ("YouDoNotPassCraftingRequirements", 1079),
("YouDoNotHaveAllTheNecessaryItems", 1080), ("NotAllTheItemsAreAvailable", 1081),
("YouMustBeInPeaceModeToTrade", 1082), ("YouAreNotTrainedInThatTradeSkill", 1083),
("YourHandsMustBeFree", 1084), ("YouCannotLinkToThatPortal", 1085),
("YouHaveSolvedThisQuestTooRecently", 1086), ("YouHaveSolvedThisQuestTooManyTimes", 1087),
("QuestUnknown", 1088), ("QuestTableCorrupt", 1089), ("QuestBad", 1090), ("QuestDuplicate", 1091),
("QuestUnsolved", 1092), ("ItemRequiresQuestToBePickedUp", 1093), ("QuestSolvedTooLongAgo", 1094),
("TradeIgnoringRequests", 1100), ("TradeSquelched", 1101), ("TradeMaxDistanceExceeded", 1102),
("TradeAlreadyTrading", 1103), ("TradeBusy", 1104), ("TradeClosed", 1105), ("TradeExpired", 1106),
("TradeItemBeingTraded", 1107), ("TradeNonEmptyContainer", 1108), ("TradeNonCombatMode", 1109),
("TradeIncomplete", 1110), ("TradeStampMismatch", 1111), ("TradeUnopened", 1112), ("TradeEmpty", 1113),
("TradeAlreadyAccepted", 1114), ("TradeOutOfSync", 1115), ("PKsMayNotUsePortal", 1116),
("NonPKsMayNotUsePortal", 1117), ("HouseAbandoned", 1118), ("HouseEvicted", 1119),
("HouseAlreadyOwned", 1120), ("HouseBuyFailed", 1121), ("HouseRentFailed", 1122), ("Hooked", 1123),
("MagicInvalidPosition", 1125), ("YouMustHaveDarkMajestyToUsePortal", 1126), ("InvalidAmmoType", 1127),
("SkillTooLow", 1128), ("YouHaveUsedAllTheHooks", 1129), ("TradeAiDoesntWant", 1130),
("HookHouseNotOwned", 1131), ("YouMustCompleteQuestToUsePortal", 1140), ("HouseNoAllegiance", 1150),
("YouMustOwnHouseToUseCommand", 1151), ("YourMonarchDoesNotOwnAMansionOrVilla", 1152),
("YourMonarchsHouseIsNotAMansionOrVilla", 1153), ("YourMonarchHasClosedTheMansion", 1154),
("YouMustBeMonarchToPurchaseDwelling", 1162), ("AllegianceTimeout", 1165),
("YourOfferOfAllegianceWasIgnored", 1166), ("ConfirmationInProgress", 1167),
("YouMustBeAMonarchToUseCommand", 1168), ("YouMustSpecifyCharacterToBoot", 1169),
("YouCantBootYourself", 1170), ("ThatCharacterDoesNotExist", 1171),
("ThatPersonIsNotInYourAllegiance", 1172), ("CantBreakFromPatronNotInAllegiance", 1173),
("YourAllegianceHasBeenDissolved", 1174), ("YourPatronsAllegianceHasBeenBroken", 1175),
("YouHaveMovedTooFar", 1176), ("TeleToInvalidPosition", 1177), ("MustHaveDarkMajestyToUse", 1178),
("YouFailToLinkWithLifestone", 1179), ("YouWanderedTooFarToLinkWithLifestone", 1180),
("YouSuccessfullyLinkWithLifestone", 1181), ("YouMustLinkToLifestoneToRecall", 1182),
("YouFailToRecallToLifestone", 1183), ("YouFailToLinkWithPortal", 1184),
("YouSuccessfullyLinkWithPortal", 1185), ("YouFailToRecallToPortal", 1186),
("YouMustLinkToPortalToRecall", 1187), ("YouFailToSummonPortal", 1188),
("YouMustLinkToPortalToSummonIt", 1189), ("YouFailToTeleport", 1190),
("YouHaveBeenTeleportedTooRecently", 1191), ("YouMustBeAnAdvocateToUsePortal", 1192),
("PortalAisNotAllowed", 1193), ("PlayersMayNotUsePortal", 1194),
("YouAreNotPowerfulEnoughToUsePortal", 1195), ("YouAreTooPowerfulToUsePortal", 1196),
("YouCannotRecallPortal", 1197), ("YouCannotSummonPortal", 1198), ("LockAlreadyUnlocked", 1199),
("YouCannotLockOrUnlockThat", 1200), ("YouCannotLockWhatIsOpen", 1201), ("KeyDoesntFitThisLock", 1202),
("LockUsedTooRecently", 1203), ("YouArentTrainedInLockpicking", 1204), ("AllegianceInfoEmptyName", 1205),
("AllegianceInfoSelf", 1206), ("AllegianceInfoTooRecent", 1207), ("AbuseNoSuchCharacter", 1208),
("AbuseReportedSelf", 1209), ("AbuseComplaintHandled", 1210), ("YouDoNotOwnThatSalvageTool", 1213),
("YouDoNotOwnThatItem", 1214), ("MaterialCannotBeCreated", 1217),
("ItemsAttemptingToSalvageIsInvalid", 1218), ("YouCannotSalvageItemsInTrading", 1219),
("YouMustBeHouseGuestToUsePortal", 1220), ("YourAllegianceRankIsTooLowToUseMagic", 1221),
("YourArcaneLoreIsTooLowToUseMagic", 1223), ("ItemDoesntHaveEnoughMana", 1224),
("YouHaveBeenInPKBattleTooRecently", 1228), ("TradeAiRefuseEmote", 1229), ("YouFailToAlterSkill", 1232),
("FellowshipDeclined", 1243), ("FellowshipTimeout", 1244), ("YouHaveFailedToAlterAttributes", 1245),
("CannotTransferAttributesWhileWieldingItem", 1248), ("YouHaveSucceededTransferringAttributes", 1249),
("HookIsDuplicated", 1250), ("ItemIsWrongTypeForHook", 1251), ("HousingChestIsDuplicated", 1252),
("HookWillBeDeleted", 1253), ("HousingChestWillBeDeleted", 1254),
("CannotSwearAllegianceWhileOwningMansion", 1255), ("YouCantDoThatWhileInTheAir", 1259),
("CannotChangePKStatusWhileRecovering", 1260), ("AdvocatesCannotChangePKStatus", 1261),
("LevelTooLowToChangePKStatusWithObject", 1262), ("LevelTooHighToChangePKStatusWithObject", 1263),
("YouFeelAHarshDissonance", 1264), ("YouArePKAgain", 1265), ("YouAreTemporarilyNoLongerPK", 1266),
("PKLiteMayNotUsePortal", 1267), ("YouArentTrainedInHealing", 1276), ("YouDontOwnThatHealingKit", 1277),
("YouCantHealThat", 1278), ("YouArentReadyToHeal", 1280), ("YouCanOnlyHealPlayers", 1281),
("LifestoneMagicProtectsYou", 1282), ("PortalEnergyProtectsYou", 1283), ("YouAreNonPKAgain", 1284),
("YoureTooCloseToYourSanctuary", 1285), ("CantDoThatTradeInProgress", 1286),
("OnlyNonPKsMayEnterPKLite", 1287), ("YouAreNowPKLite", 1288), ("YouDoNotBelongToAFellowship", 1295),
("UsingMaxHooksSilent", 1297), ("YouAreNowUsingMaxHooks", 1298), ("YouAreNoLongerUsingMaxHooks", 1299),
("YouAreNotPermittedToUseThatHook", 1302), ("LockedFellowshipCannotRecruitYou", 1305),
("ActivationNotAllowedNotOwner", 1306), ("TurbineChatIsEnabled", 1309),
("YouCannotAddPeopleToHearList", 1312), ("YouAreNowDeafTo_Screams", 1315),
("YouCanHearAllPlayersOnceAgain", 1316), ("YouChickenOut", 1318), ("YouCanPossiblySucceed", 1319),
("FellowshipIsLocked", 1320), ("TradeComplete", 1321), ("NotASalvageTool", 1322),
("CharacterNotAvailable", 1323), ("YouMustWaitToPurchaseHouse", 1330),
("YouDoNotHaveAuthorityInAllegiance", 1333), ("YouHaveMaxAccountsBanned", 1344),
("YouHaveMaxAllegianceOfficers", 1349), ("YourAllegianceOfficersHaveBeenCleared", 1350),
("YouCannotJoinChannelsWhileGagged", 1352), ("YouAreNoLongerAllegianceOfficer", 1354),
("YourAllegianceDoesNotHaveHometown", 1356), ("HookItemNotUsable_CannotOpen", 1358),
("HookItemNotUsable_CanOpen", 1359), ("MissileOutOfRange", 1360),
("MustPurchaseThroneOfDestinyToUseFunction", 1362), ("MustPurchaseThroneOfDestinyToUseItem", 1363),
("MustPurchaseThroneOfDestinyToUsePortal", 1364), ("MustPurchaseThroneOfDestinyToAccessQuest", 1365),
("YouFailedToCompleteAugmentation", 1366), ("AugmentationUsedTooManyTimes", 1367),
("AugmentationTypeUsedTooManyTimes", 1368), ("AugmentationNotEnoughExperience", 1369),
("ExitTrainingAcademyToUseCommand", 1373), ("OnlyPKsMayUseCommand", 1375),
("OnlyPKLiteMayUseCommand", 1376), ("MaxFriendsExceeded", 1377),
("ThatCharacterNotOnYourFriendsList", 1379), ("OnlyHouseOwnerCanUseCommand", 1380),
("InvalidAllegianceNameCantBeEmpty", 1381), ("InvalidAllegianceNameTooLong", 1382),
("InvalidAllegianceNameBadCharacters", 1383), ("InvalidAllegianceNameInappropriate", 1384),
("InvalidAllegianceNameAlreadyInUse", 1385), ("AllegianceNameCleared", 1387),
("InvalidAllegianceNameSameName", 1388), ("InvalidOfficerLevel", 1391),
("AllegianceOfficerTitleIsNotAppropriate", 1392), ("AllegianceNameIsTooLong", 1393),
("AllegianceOfficerTitlesCleared", 1394), ("AllegianceTitleHasIllegalChars", 1395),
("YouHaveNotPreApprovedVassals", 1401), ("YouHaveClearedPreApprovedVassal", 1404),
("CharIsAlreadyGagged", 1405), ("CharIsNotCurrentlyGagged", 1406),
("YourAllegianceChatPrivilegesRestored", 1409), ("TooManyUniqueItems", 1412),
("HeritageRequiresSpecificArmor", 1413), ("ArmorRequiresSpecificHeritage", 1414),
("OlthoiCannotInteractWithThat", 1415), ("OlthoiCannotUseLifestones", 1416),
("OlthoiVendorLooksInHorror", 1417), ("OlthoiCannotJoinFellowship", 1419),
("OlthoiCannotJoinAllegiance", 1420), ("YouCannotUseThatItem", 1421),
("ThisPersonWillNotInteractWithYou", 1422), ("OnlyOlthoiMayUsePortal", 1423),
("OlthoiMayNotUsePortal", 1424), ("YouMayNotUsePortalWithVitae", 1425),
("YouMustBeTwoWeeksOldToUsePortal", 1426), ("OlthoiCanOnlyRecallToLifestone", 1427),
("ContractError", 1428),
}),
("WeenieType", false, new (string, long)[]
{
("Undef", 0), ("Generic", 1), ("Clothing", 2), ("MissileLauncher", 3), ("Missile", 4), ("Ammunition", 5),
("MeleeWeapon", 6), ("Portal", 7), ("Book", 8), ("Coin", 9), ("Creature", 10), ("Admin", 11),
("Vendor", 12), ("HotSpot", 13), ("Corpse", 14), ("Cow", 15), ("AI", 16), ("Machine", 17), ("Food", 18),
("Door", 19), ("Chest", 20), ("Container", 21), ("Key", 22), ("Lockpick", 23), ("PressurePlate", 24),
("LifeStone", 25), ("Switch", 26), ("PKModifier", 27), ("Healer", 28), ("LightSource", 29),
("Allegiance", 30), ("UNKNOWN__GUESSEDNAME32", 31), ("SpellComponent", 32), ("ProjectileSpell", 33),
("Scroll", 34), ("Caster", 35), ("Channel", 36), ("ManaStone", 37), ("Gem", 38), ("AdvocateFane", 39),
("AdvocateItem", 40), ("Sentinel", 41), ("GSpellEconomy", 42), ("LSpellEconomy", 43), ("CraftTool", 44),
("LScoreKeeper", 45), ("GScoreKeeper", 46), ("GScoreGatherer", 47), ("ScoreBook", 48),
("EventCoordinator", 49), ("Entity", 50), ("Stackable", 51), ("HUD", 52), ("House", 53), ("Deed", 54),
("SlumLord", 55), ("Hook", 56), ("Storage", 57), ("BootSpot", 58), ("HousePortal", 59), ("Game", 60),
("GamePiece", 61), ("SkillAlterationDevice", 62), ("AttributeTransferDevice", 63), ("Hooker", 64),
("AllegianceBindstone", 65), ("InGameStatKeeper", 66), ("AugmentationDevice", 67), ("SocialManager", 68),
("Pet", 69), ("PetDevice", 70), ("CombatPet", 71),
}),
("WieldType", true, new (string, long)[]
{
("Invalid", 0), ("MeleeWeapon", 1), ("Armor", 2), ("Clothing", 4), ("Jewelry", 8),
}),
("AddRemoveEventType", false, new (string, long)[]
{
("Added", 0), ("Removed", 1),
}),
("BusyAction", false, new (string, long)[]
{
("None", 0), ("Crafting", 1), ("Wielding", 2), ("SpellCasting", 4), ("OpeningTrade", 8),
("DroppingWeenie", 16), ("GivingWeenie", 32), ("LoggingOut", 64), ("MovingWeenie", 128),
("UsingWeenie", 256), ("MovingWeenieToContainer", 512), ("TeleToLifestone", 1024), ("Portalling", 2048),
("Animating", 4096), ("ChangeCombatMode", 8192), ("TeleToMarketplace", 16384), ("TeleToPKArena", 32768),
("AdvocateTeleport", 65536), ("TeleToHouse", 131072), ("TeleToMansion", 262144),
("TeleToAllegianceHometown", 524288), ("RecallCommand", 1033216),
}),
("CastEventType", false, new (string, long)[]
{
("Untargetted", 0), ("Targetted", 1),
}),
("ChatChannel", false, new (string, long)[]
{
("None", 0), ("Allegiance", 1), ("General", 2), ("Trade", 3), ("LFG", 4), ("Roleplay", 5), ("Olthoi", 6),
("Society", 7), ("CelestialHand", 8), ("EldrytchWeb", 9), ("RadiantBlood", 10),
}),
("ClientCapability", false, new (string, long)[]
{
("ImGui", 1),
}),
("ClientConfirmationType", false, new (string, long)[]
{
("UNDEF", 0), ("ALLEGIANCE_SWEAR", 1), ("ALTER_SKILL", 2), ("ALTER_ATTRIBUTE", 3),
("FELLOWSHIP_RECRUIT", 4), ("CRAFT_INTERACTION", 5), ("USE_AUGMENTATION", 6), ("YESNO", 7),
}),
("DistanceType", false, new (string, long)[]
{
("T2D", 0), ("T3D", 1),
}),
("FellowshipEventType", false, new (string, long)[]
{
("Create", 0), ("Quit", 1), ("Dismiss", 2), ("Recruit", 3), ("Disband", 4),
}),
("ScriptStartupType", false, new (string, long)[]
{
("Manual", 0), ("Global", 1), ("Account", 2), ("Character", 3),
}),
("UseActionType", false, new (string, long)[]
{
("Default", 0), ("Vendor", 1), ("SummonPortal", 2), ("Portal", 3),
}),
};
}

View file

@ -0,0 +1,231 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using MoonSharp.Interpreter;
namespace RynthCore.Plugin.RynthLua;
/// <summary>
/// UtilityBelt-style enum values for Lua.
///
/// Typed values (the enums in <see cref="LibraryEnums.TypedEnums"/>): a table per value with
/// the raw fields <c>__enum</c> (the enum's name) and <c>__value</c> (its number), one table
/// per value per script, so <c>==</c> works by identity. They print as their name (flags as
/// "A, B"), compare and order with each other, add and subtract as numbers, concatenate as
/// text, and have <c>ToNumber()</c>, <c>HasFlags(...)</c>, <c>AddFlags(...)</c> and
/// <c>RemoveFlags(...)</c> (the last two return typed values).
///
/// Plain-number enums get the same four helpers through a number metatable (numbers have no
/// fields otherwise; indexing a number with anything else is still an error).
/// </summary>
internal static class LuaEnumValues
{
public const string EnumField = "__enum";
public const string ValueField = "__value";
private sealed class Def
{
public bool Flags;
public readonly Dictionary<long, string> Names = new();
public readonly List<(string Name, long Value)> Members = new();
}
private sealed class Cache
{
public readonly Dictionary<(string, long), DynValue> Values = new();
public readonly Dictionary<string, Table> Metas = new(StringComparer.Ordinal);
}
private static readonly Dictionary<string, Def> Defs = new(StringComparer.Ordinal);
private static readonly object DefsLock = new();
private static readonly ConditionalWeakTable<Script, Cache> Caches = new();
/// <summary>Records an enum's names (once; the first name for a number is its name).</summary>
public static void Define(string name, List<(string Name, long Value)> members, bool flags)
{
lock (DefsLock)
{
if (Defs.ContainsKey(name)) return;
var d = new Def { Flags = flags };
foreach (var (n, v) in members)
{
d.Members.Add((n, v));
d.Names.TryAdd(v, n);
}
Defs[name] = d;
}
}
/// <summary>Flags when there are more than three nonzero members and all are single bits.</summary>
public static bool LooksLikeFlags(List<(string Name, long Value)> members)
{
int n = 0;
foreach (var (_, v) in members)
{
if (v == 0) continue;
if (v < 0 || (v & (v - 1)) != 0) return false;
n++;
}
return n > 3;
}
/// <summary>Whether <paramref name="enumName"/> is a flags enum.</summary>
public static bool IsFlags(string enumName)
{
lock (DefsLock) return Defs.TryGetValue(enumName, out Def? d) && d.Flags;
}
/// <summary>"Creature", "Creature, Misc" for combined flags, or the number.</summary>
public static string NameOf(string enumName, long value)
{
Def? d;
lock (DefsLock) Defs.TryGetValue(enumName, out d);
if (d == null) return value.ToString(CultureInfo.InvariantCulture);
if (d.Names.TryGetValue(value, out string? name)) return name;
if (d.Flags && value > 0)
{
var parts = new List<string>();
long rest = value;
foreach (var (n, v) in d.Members)
if (v != 0 && (v & (v - 1)) == 0 && (rest & v) == v && !parts.Contains(n)) { parts.Add(n); rest &= ~v; }
if (rest == 0) return string.Join(", ", parts);
}
return value.ToString(CultureInfo.InvariantCulture);
}
/// <summary>The typed value of <paramref name="enumName"/> for <paramref name="value"/> in this script.</summary>
public static DynValue Get(Script s, string enumName, long value)
{
Cache cache = Caches.GetOrCreateValue(s);
if (cache.Values.TryGetValue((enumName, value), out DynValue? v)) return v;
var t = new Table(s);
t.Set(EnumField, DynValue.NewString(enumName));
t.Set(ValueField, DynValue.NewNumber(value));
t.MetaTable = Meta(s, cache, enumName);
v = DynValue.NewTable(t);
cache.Values[(enumName, value)] = v;
return v;
}
/// <summary>A typed value's enum and number.</summary>
public static bool TryRead(DynValue v, out string enumName, out long value)
{
enumName = string.Empty;
value = 0;
if (v.Type != DataType.Table) return false;
DynValue? e = v.Table.RawGet(EnumField);
DynValue? n = v.Table.RawGet(ValueField);
if (e == null || n == null || e.Type != DataType.String || n.Type != DataType.Number) return false;
enumName = e.String;
value = (long)n.Number;
return true;
}
/// <summary>True for a typed enum value (never an options table or a WorldObject).</summary>
public static bool IsTyped(DynValue v) => TryRead(v, out _, out _);
/// <summary>The number of a plain number or a typed value, else null.</summary>
public static double? AsNumber(DynValue v)
{
if (v.Type == DataType.Number) return v.Number;
return TryRead(v, out _, out long n) ? n : null;
}
private static long Bits(DynValue v, string what)
{
double? n = AsNumber(v);
if (n == null) throw new ScriptRuntimeException($"{what}: expected an enum value or a number, got {v.Type.ToString().ToLowerInvariant()}");
return (long)n.Value;
}
private static string Text(DynValue v) =>
TryRead(v, out string e, out long n) ? NameOf(e, n) : v.Type == DataType.String ? v.String : v.ToPrintString();
private static Table Meta(Script s, Cache cache, string enumName)
{
if (cache.Metas.TryGetValue(enumName, out Table? mt)) return mt;
mt = new Table(s);
var methods = new Table(s);
methods.Set("ToNumber", DynValue.NewCallback((c, a) => DynValue.NewNumber(Bits(a[0], "ToNumber"))));
methods.Set("HasFlags", DynValue.NewCallback((c, a) =>
{
long self = Bits(a[0], "HasFlags");
for (int i = 1; i < a.Count; i++)
{
long f = Bits(a[i], "HasFlags");
if ((self & f) != f) return DynValue.False;
}
return DynValue.True;
}));
methods.Set("AddFlags", DynValue.NewCallback((c, a) =>
{
long self = Bits(a[0], "AddFlags");
for (int i = 1; i < a.Count; i++) self |= Bits(a[i], "AddFlags");
return Get(s, enumName, self);
}));
methods.Set("RemoveFlags", DynValue.NewCallback((c, a) =>
{
long self = Bits(a[0], "RemoveFlags");
for (int i = 1; i < a.Count; i++) self &= ~Bits(a[i], "RemoveFlags");
return Get(s, enumName, self);
}));
mt.Set("__index", DynValue.NewTable(methods));
mt.Set("__tostring", DynValue.NewCallback((c, a) => DynValue.NewString(Text(a[0]))));
mt.Set("__eq", DynValue.NewCallback((c, a) =>
DynValue.NewBoolean(TryRead(a[0], out string e1, out long v1) && TryRead(a[1], out string e2, out long v2) && e1 == e2 && v1 == v2)));
mt.Set("__lt", DynValue.NewCallback((c, a) => DynValue.NewBoolean(Bits(a[0], "<") < Bits(a[1], "<"))));
mt.Set("__le", DynValue.NewCallback((c, a) => DynValue.NewBoolean(Bits(a[0], "<=") <= Bits(a[1], "<="))));
mt.Set("__add", DynValue.NewCallback((c, a) => DynValue.NewNumber(AsNumber(a[0]) + AsNumber(a[1]) ?? throw new ScriptRuntimeException("attempt to add an enum value and a non-number"))));
mt.Set("__sub", DynValue.NewCallback((c, a) => DynValue.NewNumber(AsNumber(a[0]) - AsNumber(a[1]) ?? throw new ScriptRuntimeException("attempt to subtract an enum value and a non-number"))));
mt.Set("__concat", DynValue.NewCallback((c, a) => DynValue.NewString(Text(a[0]) + Text(a[1]))));
cache.Metas[enumName] = mt;
return mt;
}
/// <summary>
/// Number helpers (UB's enum methods on plain-number enum values): <c>n:ToNumber()</c>,
/// <c>n:HasFlags(...)</c>, <c>n:AddFlags(...)</c>, <c>n:RemoveFlags(...)</c>. Any other key
/// is the usual "attempt to index a number value" error.
/// </summary>
public static void InstallNumberHelpers(Script s)
{
if (s.GetTypeMetatable(DataType.Number) != null) return;
var methods = new Dictionary<string, DynValue>(StringComparer.Ordinal)
{
["ToNumber"] = DynValue.NewCallback((c, a) => DynValue.NewNumber(Bits(a[0], "ToNumber"))),
["HasFlags"] = DynValue.NewCallback((c, a) =>
{
long self = Bits(a[0], "HasFlags");
for (int i = 1; i < a.Count; i++)
{
long f = Bits(a[i], "HasFlags");
if ((self & f) != f) return DynValue.False;
}
return DynValue.True;
}),
["AddFlags"] = DynValue.NewCallback((c, a) =>
{
long self = Bits(a[0], "AddFlags");
for (int i = 1; i < a.Count; i++) self |= Bits(a[i], "AddFlags");
return DynValue.NewNumber(self);
}),
["RemoveFlags"] = DynValue.NewCallback((c, a) =>
{
long self = Bits(a[0], "RemoveFlags");
for (int i = 1; i < a.Count; i++) self &= ~Bits(a[i], "RemoveFlags");
return DynValue.NewNumber(self);
}),
};
var mt = new Table(s);
mt.Set("__index", DynValue.NewCallback((c, a) =>
{
string key = a.Count > 1 ? a[1].ToPrintString() : "?";
if (a.Count > 1 && a[1].Type == DataType.String && methods.TryGetValue(a[1].String, out DynValue? fn)) return fn;
throw new ScriptRuntimeException($"attempt to index a number value (field '{key}')");
}));
s.SetTypeMetatable(DataType.Number, mt);
}
}

View file

@ -0,0 +1,69 @@
using System;
using System.Collections.Generic;
namespace RynthCore.Plugin.RynthLua;
/// <summary>
/// Enum numbering every API area uses (World classifies objects with ObjectClass, Character
/// reads skills by SkillId, Library exposes the same tables as globals). ObjectClass follows
/// Decal's / UtilityBelt's order, SkillId and AttributeId AC's, so UB scripts' numbers match.
/// </summary>
internal static class LuaEnums
{
public static readonly string[] ObjectClass =
{
"Unknown", "MeleeWeapon", "Armor", "Clothing", "Jewelry", "Monster", "Food", "Money", "Misc",
"MissileWeapon", "Container", "Gem", "SpellComponent", "Key", "Portal", "TradeNote", "ManaStone",
"Plant", "BaseCooking", "BaseAlchemy", "BaseFletching", "CraftedCooking", "CraftedAlchemy",
"CraftedFletching", "Player", "Vendor", "Door", "Corpse", "Lifestone", "HealingKit", "Lockpick",
"WandStaffOrb", "Bundle", "Book", "Journal", "Sign", "Housing", "Npc", "Foci", "Salvage", "Ust",
"Services", "Scroll",
};
public static readonly Dictionary<string, int> SkillId = new(StringComparer.OrdinalIgnoreCase)
{
["Axe"] = 1, ["Bow"] = 2, ["Crossbow"] = 3, ["Dagger"] = 4, ["Mace"] = 5, ["MeleeDefense"] = 6,
["MissileDefense"] = 7, ["Sling"] = 8, ["Spear"] = 9, ["Staff"] = 10, ["Sword"] = 11,
["ThrownWeapon"] = 12, ["UnarmedCombat"] = 13, ["ArcaneLore"] = 14, ["MagicDefense"] = 15,
["ManaConversion"] = 16, ["Spellcraft"] = 17, ["ItemTinkering"] = 18, ["AssessPerson"] = 19,
["Deception"] = 20, ["Healing"] = 21, ["Jump"] = 22, ["Lockpick"] = 23, ["Run"] = 24,
["Awareness"] = 25, ["ArmsAndArmorRepair"] = 26, ["AssessCreature"] = 27, ["WeaponTinkering"] = 28,
["ArmorTinkering"] = 29, ["MagicItemTinkering"] = 30, ["CreatureEnchantment"] = 31,
["ItemEnchantment"] = 32, ["LifeMagic"] = 33, ["WarMagic"] = 34, ["Leadership"] = 35, ["Loyalty"] = 36,
["Fletching"] = 37, ["Alchemy"] = 38, ["Cooking"] = 39, ["Salvaging"] = 40, ["TwoHandedCombat"] = 41,
["Gearcraft"] = 42, ["VoidMagic"] = 43, ["HeavyWeapons"] = 44, ["LightWeapons"] = 45,
["FinesseWeapons"] = 46, ["MissileWeapons"] = 47, ["Shield"] = 48, ["DualWield"] = 49,
["Recklessness"] = 50, ["SneakAttack"] = 51, ["DirtyFighting"] = 52, ["Challenge"] = 53, ["Summoning"] = 54,
};
public static readonly Dictionary<string, int> AttributeId = new(StringComparer.OrdinalIgnoreCase)
{
["Strength"] = 1, ["Endurance"] = 2, ["Quickness"] = 3, ["Coordination"] = 4, ["Focus"] = 5, ["Self"] = 6,
};
/// <summary>
/// Health 1, Stamina 3, Mana 5: UtilityBelt's VitalId numbering (AC's max-vital ids,
/// the same numbers InqAttribute2nd uses).
/// </summary>
public static readonly Dictionary<string, int> VitalId = new(StringComparer.OrdinalIgnoreCase)
{
["Health"] = 1, ["Stamina"] = 3, ["Mana"] = 5,
};
public static readonly Dictionary<string, int> CombatMode = new(StringComparer.OrdinalIgnoreCase)
{
["NonCombat"] = 1, ["Melee"] = 2, ["Missile"] = 4, ["Magic"] = 8,
};
public static string CombatModeName(int mode) => mode switch
{
1 => "NonCombat", 2 => "Melee", 4 => "Missile", 8 => "Magic", _ => "Undef",
};
public static int ObjectClassOf(string name)
{
for (int i = 0; i < ObjectClass.Length; i++)
if (ObjectClass[i].Equals(name, StringComparison.OrdinalIgnoreCase)) return i;
return -1;
}
}

View file

@ -0,0 +1,85 @@
using System;
using System.IO;
namespace RynthCore.Plugin.RynthLua;
/// <summary>Starter scripts (or the scripts from RynthAi's old folder), written only when the Scripts folder doesn't exist yet.</summary>
internal static class LuaExamples
{
public static void EnsureWritten(Action<string> log)
{
try
{
if (Directory.Exists(LuaScriptHost.ScriptFolder)) return;
Directory.CreateDirectory(LuaScriptHost.ScriptFolder);
// Scripts written while Lua lived in RynthAi come along (the old folder is left as is).
if (Directory.Exists(LuaScriptHost.LegacyScriptFolder))
{
int copied = 0;
foreach (string f in Directory.GetFiles(LuaScriptHost.LegacyScriptFolder, "*.lua"))
{
File.Copy(f, Path.Combine(LuaScriptHost.ScriptFolder, Path.GetFileName(f)), overwrite: false);
copied++;
}
log($"[Lua] Copied {copied} script(s) from {LuaScriptHost.LegacyScriptFolder}.");
if (copied > 0) return;
}
Write("Example - Hello", Hello);
Write("Example - Wisp Essence", Wisp);
Write("Example - Tells", Tells);
}
catch (Exception ex) { log($"[Lua] Couldn't write example scripts: {ex.Message}"); }
}
private static void Write(string name, string text)
=> File.WriteAllText(Path.Combine(LuaScriptHost.ScriptFolder, name + ".lua"), text.Replace("\r\n", "\n"));
private const string Hello = """
-- Prints who and where you are, then counts down.
print("Hello, " .. me.name)
print(("Health %d / %d Mana %d / %d"):format(me.health, me.maxhealth, me.mana, me.maxmana))
print("You are at " .. me.coords)
for i = 3, 1, -1 do
print(i .. "...")
sleep(1000) -- sleep never freezes the game
end
chat("Hello from Lua!") -- shows in your chat window only
""";
private const string Wisp = """
-- Keeps a pet essence charged: when it has no uses left, refills it
-- with an Encapsulated Spirit. Change the names to match your items.
local ESSENCE = "Imperial Wisp Essence"
local SPIRIT = "Encapsulated Spirit"
while true do
local essence = meta.wobjectfindininventorybyname(ESSENCE)
if essence ~= 0 then
local uses = meta.wobjectgetintprop(essence, 92) -- 92 = uses left
if uses < 1 then
if meta.getitemcountininventorybyname(SPIRIT) > 0 then
print("Refilling " .. ESSENCE)
command("/ub usei " .. SPIRIT .. " on " .. ESSENCE)
sleep(3000)
else
print("Out of " .. SPIRIT .. "; stopping.")
stop()
end
end
end
sleep(5000)
end
""";
private const string Tells = """
-- Runs in the background and logs every tell you get to the Lua console.
-- Scripts that only register events keep running until you press Stop.
on("chat", function(text, chatType)
if text:find("tells you") then
print(os.date("%H:%M") .. " " .. text)
end
end)
print("Listening for tells. Press Stop to end.")
""";
}

View file

@ -0,0 +1,77 @@
using MoonSharp.Interpreter;
namespace RynthCore.Plugin.RynthLua;
/// <summary>
/// The lists the API returns (World.GetAll, WorldObject.Items, Character.Inventory, ...):
/// plain 1-based Lua tables, so <c>#list</c>, <c>list[i]</c> and <c>ipairs(list)</c> work,
/// with a metatable that also lets a script
/// <list type="bullet">
/// <item>iterate one directly, <c>for wo in list do ... end</c> (the way a CLR list is
/// iterated in UtilityBelt's Lua), and</item>
/// <item>call one: a plain list returns itself (so the older call forms such as
/// <c>wo:Items()</c> keep working), a list made with an onCall function passes the call on
/// (<c>game.Character.Inventory(filter)</c>).</item>
/// </list>
/// The metatable is made once per script, in Lua, so iteration and filter functions stay
/// ordinary Lua code (they can sleep).
/// </summary>
internal static class LuaLists
{
private const string RegistryKey = "rynth.lists";
private const string Factory = """
local cursor = setmetatable({}, { __mode = 'k' })
local function iterate(self, control)
local i
if control == nil then
i = 1
else
local c = cursor[self]
if c ~= nil and rawequal(self[c], control) then
i = c + 1
else
for k = 1, #self do
if rawequal(self[k], control) then i = k + 1; break end
end
if i == nil then return nil end
end
end
cursor[self] = i
return self[i]
end
local plain = { __call = function(self, ...)
local a, b = ...
if select('#', ...) == 2 and a == nil then return iterate(self, b) end
return self
end }
local function make(items, onCall)
if onCall == nil then return setmetatable(items, plain) end
return setmetatable(items, { __call = function(self, ...)
local a, b = ...
if select('#', ...) == 2 and a == nil then return iterate(self, b) end
return onCall(...)
end })
end
return { plain = plain, make = make }
""";
private static Table Lib(Script s)
{
DynValue lib = s.Registry.Get(RegistryKey);
if (lib.Type == DataType.Table) return lib.Table;
lib = s.DoString(Factory, null, "rynth-lists");
s.Registry.Set(RegistryKey, lib);
return lib.Table;
}
/// <summary>Gives <paramref name="list"/> the list metatable and returns it.</summary>
public static DynValue Wrap(Script s, Table list)
{
list.MetaTable = Lib(s).Get("plain").Table;
return DynValue.NewTable(list);
}
/// <summary><c>make(items [, onCall])</c> for Lua glue code.</summary>
public static DynValue MakeFunction(Script s) => Lib(s).Get("make");
}

View file

@ -0,0 +1,416 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using MoonSharp.Interpreter;
namespace RynthCore.Plugin.RynthLua;
/// <summary>
/// One script's Lua state (MoonSharp, Lua 5.2), run on the plugin pump thread.
///
/// Every piece of script code runs as a coroutine ("thread") resumed from
/// <see cref="Tick"/>: the main chunk, each event handler call and each
/// <c>spawn</c>. <c>sleep(ms)</c> parks the thread until its wake time, <c>await(action)</c>
/// until the action's <c>IsFinished</c> is true, and MoonSharp's auto-yield pauses any
/// thread that runs too long without sleeping, so an endless loop slows the script down
/// instead of freezing the client. A script stays running while it has live threads,
/// handlers (v1 <c>on</c>, v2 events, commands) or a global <c>OnBotTick</c>; Stop clears them.
/// </summary>
internal sealed class LuaScriptHost
{
/// <summary>C:\Games\RynthSuite\RynthLua\Scripts (see <see cref="RynthLuaPaths"/>).</summary>
public static string ScriptFolder => RynthLuaPaths.Scripts;
/// <summary>Where scripts lived while Lua was part of RynthAi (copied over once, then left alone).</summary>
public static string LegacyScriptFolder => RynthLuaPaths.LegacyScripts;
private const int MaxConsoleLines = 400;
private const int AutoYieldCounter = 5_000; // VM instructions before a forced pause
private sealed class LuaThread
{
public DynValue Co = DynValue.Nil;
public long WakeAt;
public Func<bool>? WaitFor; // await: resume only once this is true
public DynValue[] Args = Array.Empty<DynValue>();
public bool Started;
}
private readonly Action<string> _log;
private readonly Action<Script, LuaScriptHost> _registerApi;
private readonly List<LuaThread> _threads = new();
private readonly Dictionary<string, List<DynValue>> _handlers = new(StringComparer.OrdinalIgnoreCase);
private readonly LinkedList<string> _console = new();
private readonly object _consoleLock = new();
private Script? _script;
private LuaThread? _current;
private int _resumeFrom; // round-robin start within this script
/// <summary>The script's folder for <c>require</c> (null: single-file script, only built-in modules).</summary>
public string? Folder { get; set; }
/// <summary>Built-in modules for <c>require(name)</c>, created per script on first use.</summary>
public Func<Script, string, DynValue?>? ResolveModule;
/// <summary>Extra "keeps the script alive" count (v2 events, commands) from the ScriptContext.</summary>
public Func<int>? ExtraHandlers;
/// <summary>Called once when the script stops for any reason (cleanup of v2 registrations).</summary>
public Action<string>? Stopped;
/// <summary>Runs when the script calls stop(), before its state goes away (game.OnScriptEnd).</summary>
public Action? BeforeScriptStop;
public bool Running => _script != null && (_threads.Count > 0 || HandlerCount > 0 || HasBotTick || (ExtraHandlers?.Invoke() ?? 0) > 0);
public bool Loaded => _script != null;
public Script? Lua => _script;
/// <summary>True while the RynthAi macro runs; gates OnBotTick (the Decal RynthAi's hook).</summary>
public Func<bool>? MacroRunning;
private const long BotTickMs = 250;
private long _nextBotTick;
private LuaThread? _botTickThread;
private bool HasBotTick => _script != null && _script.Globals.Get("OnBotTick").Type == DataType.Function;
public string ScriptName { get; private set; } = string.Empty;
public string Status { get; private set; } = string.Empty;
public int ConsoleSeq { get; private set; }
private int HandlerCount
{
get { int n = 0; foreach (var l in _handlers.Values) n += l.Count; return n; }
}
public LuaScriptHost(Action<string> log, Action<Script, LuaScriptHost> registerApi)
{
_log = log;
_registerApi = registerApi;
}
// ── Console ─────────────────────────────────────────────────────────────
public void Print(string text)
{
lock (_consoleLock)
{
foreach (string line in text.Replace("\r", "").Split('\n'))
{
_console.AddLast(line);
if (_console.Count > MaxConsoleLines) _console.RemoveFirst();
}
ConsoleSeq++;
}
}
public string ConsoleText()
{
lock (_consoleLock) return string.Join("\n", _console);
}
public void ClearConsole()
{
lock (_consoleLock) { _console.Clear(); ConsoleSeq++; }
}
// ── Files ───────────────────────────────────────────────────────────────
/// <summary>Single-file scripts (<c>Name.lua</c>) in the scripts folder.</summary>
public static List<string> ListScripts()
{
var list = new List<string>();
try
{
if (Directory.Exists(ScriptFolder))
foreach (string f in Directory.GetFiles(ScriptFolder, "*.lua"))
list.Add(Path.GetFileNameWithoutExtension(f));
}
catch { }
list.Sort(StringComparer.OrdinalIgnoreCase);
return list;
}
/// <summary>Maps a script name to its single file, or null when the name can't be a file name.</summary>
public static string? PathFor(string name)
{
string n = (name ?? string.Empty).Trim();
if (n.EndsWith(".lua", StringComparison.OrdinalIgnoreCase)) n = n[..^4].TrimEnd();
if (n.Length == 0 || n.IndexOfAny(Path.GetInvalidFileNameChars()) >= 0) return null;
return Path.Combine(ScriptFolder, n + ".lua");
}
// ── Run / stop ──────────────────────────────────────────────────────────
public void Run(string code, string name)
{
if (_script != null) Stop("replaced by a new run");
ScriptName = name ?? string.Empty;
var script = new Script(CoreModules.Preset_SoftSandbox | CoreModules.Coroutine | CoreModules.OS_Time);
script.Options.DebugPrint = s => Print(s);
_script = script;
try
{
RegisterCore(script);
_registerApi(script, this);
DynValue chunk = script.LoadString(code, null, ScriptName.Length > 0 ? ScriptName : "editor");
Start(chunk, Array.Empty<DynValue>());
Status = string.Empty;
Print($"--- running {(ScriptName.Length > 0 ? ScriptName : "editor script")} ---");
_log($"[Lua] Started {(ScriptName.Length > 0 ? ScriptName : "editor script")}");
}
catch (InterpreterException ex)
{
Print("error: " + (ex.DecoratedMessage ?? ex.Message));
Stop("failed to load");
}
catch (Exception ex)
{
Print("error: " + ex.Message);
Stop("failed to load");
}
}
/// <summary>Runs extra code inside this running script's state (/lua execin), as a new thread.</summary>
public bool Exec(string code)
{
if (_script == null) return false;
try
{
DynValue chunk = _script.LoadString(code, null, "exec");
Start(chunk, Array.Empty<DynValue>());
return true;
}
catch (InterpreterException ex)
{
Print("error: " + (ex.DecoratedMessage ?? ex.Message));
return false;
}
}
public void Stop(string reason = "stopped")
{
bool was = _script != null;
_threads.Clear();
_handlers.Clear();
_current = null;
_botTickThread = null;
_script = null;
if (was)
{
Status = $"Lua: {reason}";
Print($"--- {reason} ---");
_log($"[Lua] {(ScriptName.Length > 0 ? ScriptName : "editor script")}: {reason}");
try { Stopped?.Invoke(reason); } catch { }
}
}
/// <summary>Starts <paramref name="fn"/> as a new script thread.</summary>
public void Start(DynValue fn, DynValue[] args)
{
if (_script == null || fn.Type != DataType.Function) return;
DynValue co = _script.CreateCoroutine(fn);
co.Coroutine.AutoYieldCounter = AutoYieldCounter;
_threads.Add(new LuaThread { Co = co, Args = args });
}
/// <summary>Calls every v1 handler registered for <paramref name="evt"/>, each on its own thread.</summary>
public void Fire(string evt, params DynValue[] args)
{
if (_script == null || !_handlers.TryGetValue(evt, out var list) || list.Count == 0) return;
foreach (DynValue fn in list.ToArray()) Start(fn, args);
}
public bool HasHandlers(string evt)
=> _script != null && _handlers.TryGetValue(evt, out var l) && l.Count > 0;
// ── Scheduler ───────────────────────────────────────────────────────────
/// <summary>
/// Resumes this script's threads that are due, until <paramref name="deadline"/>
/// (a Stopwatch timestamp). Threads are taken round-robin, so a busy one can't
/// starve the others.
/// </summary>
public void Tick(long deadline)
{
if (_script == null) return;
if (!Running) { Stop("finished"); return; }
// OnBotTick(): every 250 ms while the macro runs, one call at a time.
long nowMs = Environment.TickCount64;
if (nowMs >= _nextBotTick && HasBotTick && MacroRunning?.Invoke() == true
&& (_botTickThread == null || !_threads.Contains(_botTickThread)))
{
_nextBotTick = nowMs + BotTickMs;
Start(_script.Globals.Get("OnBotTick"), Array.Empty<DynValue>());
_botTickThread = _threads[^1];
}
bool OverBudget() => System.Diagnostics.Stopwatch.GetTimestamp() >= deadline;
int n = _threads.Count;
if (n == 0) return;
if (_resumeFrom >= n) _resumeFrom = 0;
// Threads that haven't run yet go first, in the order they were started (event handler
// calls then run in the order their events happened); the running ones take turns
// round-robin, so a busy one can't starve the others.
var order = new List<LuaThread>(n);
foreach (LuaThread t in _threads) if (!t.Started) order.Add(t);
for (int k = 0; k < n; k++)
{
LuaThread t = _threads[(_resumeFrom + k) % n];
if (t.Started) order.Add(t);
}
_resumeFrom++;
foreach (LuaThread t in order)
{
if (_script == null) return; // the script called stop()
if (!_threads.Contains(t)) continue; // removed by an earlier thread (stop in a handler, ...)
if (Environment.TickCount64 < t.WakeAt) continue;
if (t.WaitFor != null)
{
bool ready;
try { ready = t.WaitFor(); } catch { ready = true; }
if (!ready) continue;
t.WaitFor = null;
}
_current = t;
try
{
while (_script != null)
{
DynValue r = t.Started ? t.Co.Coroutine.Resume() : t.Co.Coroutine.Resume(t.Args);
t.Started = true;
if (t.Co.Coroutine.State == CoroutineState.Dead) break;
// Forced (auto) yield: keep going while this tick has budget.
if (r.Type == DataType.YieldRequest && !OverBudget()) continue;
break;
}
}
catch (InterpreterException ex)
{
Print("error: " + (ex.DecoratedMessage ?? ex.Message));
_threads.Remove(t);
continue;
}
catch (Exception ex)
{
Print("error: " + ex.Message);
_threads.Remove(t);
continue;
}
finally { _current = null; }
if (_script == null) return;
if (t.Co.Coroutine.State == CoroutineState.Dead) _threads.Remove(t);
if (OverBudget()) break;
}
}
// ── Core globals ────────────────────────────────────────────────────────
private readonly Dictionary<string, DynValue> _modules = new(StringComparer.OrdinalIgnoreCase);
private void RegisterCore(Script s)
{
_modules.Clear();
// sleep(ms): park the calling thread. Implemented as a CLR call that
// sets the wake time, then a Lua-side yield (a CLR callback can't
// yield by itself).
s.Globals["__rynth_setwake"] = DynValue.NewCallback((ctx, a) =>
{
if (_current != null)
_current.WakeAt = Environment.TickCount64 + (long)Math.Max(0, a.Count > 0 && a[0].Type == DataType.Number ? a[0].Number : 0);
return DynValue.Nil;
});
// await(action): park until the object's IsFinished field is true, then return it.
s.Globals["__rynth_setawait"] = DynValue.NewCallback((ctx, a) =>
{
DynValue obj = a.Count > 0 ? a[0] : DynValue.Nil;
if (obj.Type != DataType.Table)
throw new ScriptRuntimeException("await(action) needs an action (what game.Actions... returns)");
Table t = obj.Table;
if (_current != null) _current.WaitFor = () => t.RawGet("IsFinished")?.CastToBool() == true;
return DynValue.Nil;
});
s.Globals["on"] = DynValue.NewCallback((ctx, a) =>
{
string evt = a.Count > 0 ? a[0].CastToString() ?? "" : "";
DynValue fn = a.Count > 1 ? a[1] : DynValue.Nil;
if (evt.Length == 0 || fn.Type != DataType.Function)
throw new ScriptRuntimeException("on(event, function) needs an event name and a function");
if (!_handlers.TryGetValue(evt, out var list)) _handlers[evt] = list = new List<DynValue>();
list.Add(fn);
return DynValue.Nil;
});
s.Globals["off"] = DynValue.NewCallback((ctx, a) =>
{
string evt = a.Count > 0 ? a[0].CastToString() ?? "" : "";
if (a.Count > 1 && a[1].Type == DataType.Function && _handlers.TryGetValue(evt, out var list))
list.RemoveAll(f => f.Equals(a[1]));
else
_handlers.Remove(evt);
return DynValue.Nil;
});
s.Globals["spawn"] = DynValue.NewCallback((ctx, a) =>
{
if (a.Count == 0 || a[0].Type != DataType.Function)
throw new ScriptRuntimeException("spawn(function, ...) needs a function");
var rest = new DynValue[Math.Max(0, a.Count - 1)];
for (int i = 1; i < a.Count; i++) rest[i - 1] = a[i];
Start(a[0], rest);
return DynValue.Nil;
});
s.Globals["stop"] = DynValue.NewCallback((ctx, a) =>
{
Action? before = BeforeScriptStop;
BeforeScriptStop = null;
try { before?.Invoke(); } catch { }
Stop("stopped by script");
return DynValue.Nil;
});
s.Globals["clock"] = DynValue.NewCallback((ctx, a) => DynValue.NewNumber(Environment.TickCount64));
// require(name): a built-in module, else a .lua file in this script's folder (never outside it).
s.Globals["require"] = DynValue.NewCallback((ctx, a) =>
{
string name = (a.Count > 0 ? a[0].CastToString() : null)?.Trim() ?? "";
if (name.Length == 0) throw new ScriptRuntimeException("require(name) needs a module name");
if (_modules.TryGetValue(name, out DynValue? cached)) return cached;
DynValue? builtIn = ResolveModule?.Invoke(s, name);
if (builtIn != null) { _modules[name] = builtIn; return builtIn; }
if (Folder == null)
throw new ScriptRuntimeException($"require(\"{name}\"): no such module (single-file scripts can only require built-in modules)");
string rel = name.Replace('.', Path.DirectorySeparatorChar);
if (rel.EndsWith(".lua", StringComparison.OrdinalIgnoreCase)) rel = rel[..^4];
string root = Path.GetFullPath(Folder);
string file = Path.GetFullPath(Path.Combine(root, rel + ".lua"));
if (!file.StartsWith(root.TrimEnd(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase))
throw new ScriptRuntimeException($"require(\"{name}\"): outside the script's folder");
if (!File.Exists(file))
throw new ScriptRuntimeException($"require(\"{name}\"): no module or file {Path.GetFileName(file)} in the script's folder");
DynValue loaded = s.DoString(File.ReadAllText(file), null, Path.GetFileName(file));
DynValue result = loaded.IsNil() ? DynValue.True : loaded;
_modules[name] = result;
return result;
});
s.DoString(@"
function sleep(ms) __rynth_setwake(ms or 0); coroutine.yield() end
wait = sleep
function await(action) __rynth_setawait(action); coroutine.yield(); return action end
function waitfor(cond, timeout)
local deadline = timeout and (clock() + timeout) or nil
while not cond() do
if deadline and clock() >= deadline then return false end
sleep(100)
end
return true
end
", null, "rynth-core");
}
}

View file

@ -0,0 +1,42 @@
using System;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthLua;
internal static class NavCoordinateHelper
{
public static bool TryGetNavCoords(RynthCoreHost host, out double northSouth, out double eastWest)
{
northSouth = 0;
eastWest = 0;
if (host.TryGetCurCoords(out northSouth, out eastWest))
return true;
if (host.TryGetPlayerPose(out uint fallbackCellId, out float fallbackX, out float fallbackY, out _, out _, out _, out _, out _))
return TryConvertPoseToCoords(fallbackCellId, fallbackX, fallbackY, out northSouth, out eastWest);
return false;
}
internal static bool TryConvertPoseToCoords(uint objCellId, float x, float y, out double northSouth, out double eastWest)
{
northSouth = 0;
eastWest = 0;
uint landblock = objCellId >> 16;
if (landblock == 0)
return false;
int lbX = (int)((objCellId >> 24) & 0xFF);
int lbY = (int)((objCellId >> 16) & 0xFF);
// Match the classic radar/Coordinates() basis exactly:
// EW = ((Landcell >> 24) * 8 + X / 24 - 1019.5) / 10
// NS = (((Landcell >> 16) & 0xFF) * 8 + Y / 24 - 1019.5) / 10
eastWest = (lbX * 8.0 + x / 24.0 - 1019.5) / 10.0;
northSouth = (lbY * 8.0 + y / 24.0 - 1019.5) / 10.0;
return !double.IsNaN(northSouth) && !double.IsNaN(eastWest) &&
!double.IsInfinity(northSouth) && !double.IsInfinity(eastWest);
}
}

View file

@ -0,0 +1,131 @@
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text.Json;
using System.Threading;
using RynthCore.PluginCore;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthLua;
public static unsafe class PluginExports
{
internal static readonly RynthPluginRuntime<RynthLuaPlugin> Runtime = new();
[UnmanagedCallersOnly(EntryPoint = "RynthPluginInit", CallConvs = new[] { typeof(CallConvCdecl) })]
private static int Init(RynthCoreApiNative* api) => Runtime.Init(api);
[UnmanagedCallersOnly(EntryPoint = "RynthPluginShutdown", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void Shutdown() => Runtime.Shutdown();
[UnmanagedCallersOnly(EntryPoint = "RynthPluginName", CallConvs = new[] { typeof(CallConvCdecl) })]
public static IntPtr GetName() => RynthLuaPlugin.NamePointer;
[UnmanagedCallersOnly(EntryPoint = "RynthPluginVersion", CallConvs = new[] { typeof(CallConvCdecl) })]
public static IntPtr GetVersion() => RynthLuaPlugin.VersionPointer;
[UnmanagedCallersOnly(EntryPoint = "RynthPluginTick", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void Tick() => Runtime.OnTick();
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnLoginComplete", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnLoginComplete() => Runtime.OnLoginComplete();
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnLogout", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnLogout() => Runtime.OnLogout();
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnChatWindowText", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnChatWindowText(IntPtr textUtf16, int chatType, IntPtr eatFlag) => Runtime.OnChatWindowText(textUtf16, chatType, eatFlag);
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnChatBarEnter", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnChatBarEnter(IntPtr textUtf16, IntPtr eatFlag) => Runtime.OnChatBarEnter(textUtf16, eatFlag);
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnSelectedTargetChange", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnSelectedTargetChange(uint currentTargetId, uint previousTargetId) => Runtime.OnSelectedTargetChange(currentTargetId, previousTargetId);
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnCreateObject", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnCreateObject(uint objectId) => Runtime.OnCreateObject(objectId);
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnDeleteObject", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnDeleteObject(uint objectId) => Runtime.OnDeleteObject(objectId);
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnViewObjectContents", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnViewObjectContents(uint objectId) => Runtime.OnViewObjectContents(objectId);
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnStopViewingObjectContents", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnStopViewingObjectContents(uint objectId) => Runtime.OnStopViewingObjectContents(objectId);
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnVendorOpen", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnVendorOpen(uint vendorId) => Runtime.OnVendorOpen(vendorId);
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnVendorClose", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnVendorClose(uint vendorId) => Runtime.OnVendorClose(vendorId);
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnCombatModeChange", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnCombatModeChange(int currentCombatMode, int previousCombatMode) => Runtime.OnCombatModeChange(currentCombatMode, previousCombatMode);
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnUpdateHealth", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnUpdateHealth(uint targetId, float healthRatio, uint currentHealth, uint maxHealth) => Runtime.OnUpdateHealth(targetId, healthRatio, currentHealth, maxHealth);
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnCombatDamage", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnCombatDamage(uint damage, uint damageType, uint crit, uint isAttacker) => Runtime.OnCombatDamage(damage, damageType, crit, isAttacker);
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnKillNotification", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnKillNotification(IntPtr textUtf16) => Runtime.OnKillNotification(textUtf16);
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnEnchantmentAdded", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnEnchantmentAdded(uint spellId, double durationSeconds) => Runtime.OnEnchantmentAdded(spellId, durationSeconds);
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnEnchantmentRemoved", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnEnchantmentRemoved(uint enchantmentId) => Runtime.OnEnchantmentRemoved(enchantmentId);
// Plugin commands (host SendPluginCommand, v64): RynthAi forwards "/ra lua ..." here as
// ("lua", "run X") so metas' chat actions keep working. Copied, applied on the next tick.
[UnmanagedCallersOnly(EntryPoint = "RynthPluginApplyRemoteCommand", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void ApplyRemoteCommand(IntPtr actionAnsi, IntPtr valueAnsi)
{
try
{
string action = actionAnsi == IntPtr.Zero ? "" : Marshal.PtrToStringAnsi(actionAnsi) ?? "";
string value = valueAnsi == IntPtr.Zero ? "" : Marshal.PtrToStringAnsi(valueAnsi) ?? "";
Runtime.Plugin?.ApplyRemoteCommand(action, value);
}
catch { }
}
// ── Lua panel (engine UI/Data/LuaData.cs) ────────────────────────────────
// Same export names the panel used on RynthAi; the engine now asks RynthLua.
// Called on the plugin pump thread (UiDataHub runs right after TickAll).
private static IntPtr _luaPtr = IntPtr.Zero;
[UnmanagedCallersOnly(EntryPoint = "RynthPluginGetLuaJson", CallConvs = new[] { typeof(CallConvCdecl) })]
public static IntPtr GetLuaJson()
{
try
{
string json = Runtime.Plugin?.BuildLuaJson() ?? "{}";
IntPtr fresh = Marshal.StringToCoTaskMemUTF8(json);
IntPtr old = Interlocked.Exchange(ref _luaPtr, fresh);
if (old != IntPtr.Zero) Marshal.FreeCoTaskMem(old);
return fresh;
}
catch
{
return IntPtr.Zero;
}
}
[UnmanagedCallersOnly(EntryPoint = "RynthPluginSendLuaCommand", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void SendLuaCommand(IntPtr utf8Json)
{
try
{
if (utf8Json == IntPtr.Zero) return;
string? json = Marshal.PtrToStringUTF8(utf8Json);
if (string.IsNullOrEmpty(json)) return;
var cmd = JsonSerializer.Deserialize(json, RynthLuaJsonContext.Default.LuaCommand);
if (cmd != null) Runtime.Plugin?.EnqueueLuaCommand(cmd);
}
catch { }
}
}

View file

@ -0,0 +1,153 @@
using System;
using System.Runtime.InteropServices;
using RynthCore.Plugin.Shared;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthLua;
/// <summary>
/// RynthAi's "RynthAi.Script" interface (Shared/RynthAiScriptApi.cs), resolved through the
/// host (API v68) and wrapped as plain C# calls. Everything here runs on the plugin pump
/// thread. The table is looked up lazily, and RynthLuaPlugin.OnTick resets it every tick:
/// RynthAi may load after RynthLua, be reloaded (its code unloaded), or not be installed at all (then every call reports
/// "RynthAi isn't loaded" and scripts that only use chat, timers and the game keep working).
/// </summary>
internal sealed unsafe class RynthAiBridge
{
public const string NotLoaded = "RynthAi isn't loaded (needs RynthAi and RynthCore 2026.9.29 or newer)";
private readonly RynthCoreHost _host;
private RynthAiScriptApiV1* _t;
private bool _checked;
private long _checkedAt;
private const long RecheckMs = 3000;
public RynthAiBridge(RynthCoreHost host) => _host = host;
/// <summary>True when RynthAi's interface is there right now.</summary>
public bool Available => Table != null;
private RynthAiScriptApiV1* Table
{
get
{
long now = Environment.TickCount64;
if (_checked && now - _checkedAt < RecheckMs) return _t;
_checked = true;
_checkedAt = now;
IntPtr p = _host.GetPluginInterface("RynthAi", RynthAiScriptApiV1.InterfaceName, RynthAiScriptApiV1.InterfaceVersion);
var t = (RynthAiScriptApiV1*)p;
_t = t != null && t->Version >= 1 && t->StructSize >= (uint)sizeof(RynthAiScriptApiV1) ? t : null;
return _t;
}
}
/// <summary>Forget the table (logout, RynthAi reload); the next call looks it up again.</summary>
public void Reset()
{
_t = null;
_checked = false;
}
private static string Copy(byte* s) => s == null ? string.Empty : Marshal.PtrToStringUTF8((IntPtr)s) ?? string.Empty;
/// <summary>A UTF-8 copy of <paramref name="s"/> for the duration of one call.</summary>
private readonly ref struct Utf8
{
public readonly IntPtr Ptr;
public Utf8(string s) => Ptr = Marshal.StringToCoTaskMemUTF8(s ?? string.Empty);
public byte* P => (byte*)Ptr;
public void Dispose() => Marshal.FreeCoTaskMem(Ptr);
}
public bool Evaluate(string expression, out string result)
{
var t = Table;
if (t == null) { result = NotLoaded; return false; }
using var e = new Utf8(expression);
byte* r = null;
int ok = t->Evaluate(e.P, &r);
result = Copy(r);
return ok != 0;
}
public string? GetSetting(string name)
{
var t = Table;
if (t == null) return null;
using var n = new Utf8(name);
byte* r = null;
return t->GetSetting(n.P, &r) != 0 ? Copy(r) : null;
}
public bool SetSetting(string name, string value)
{
var t = Table;
if (t == null) return false;
using var n = new Utf8(name);
using var v = new Utf8(value);
return t->SetSetting(n.P, v.P) != 0;
}
public string[] SettingNames()
{
var t = Table;
if (t == null) return Array.Empty<string>();
byte* r = null;
return t->GetSettingNames(&r) != 0 ? Copy(r).Split('\n', StringSplitOptions.RemoveEmptyEntries) : Array.Empty<string>();
}
public bool MacroRunning
{
get { var t = Table; return t != null && t->IsMacroRunning() != 0; }
set { var t = Table; if (t != null) t->SetMacroRunning(value ? 1 : 0); }
}
public bool GoTo(double ns, double ew)
{
var t = Table;
return t != null && t->NavGoTo(ns, ew) != 0;
}
public void Stop()
{
var t = Table;
if (t != null) t->NavStop();
}
public bool FindNearest(string name, bool portalOrNpcOnly, out uint id, out double distance)
{
id = 0; distance = -1;
var t = Table;
if (t == null) return false;
using var n = new Utf8(name);
uint found = 0; double d = -1;
if (t->FindNearest(n.P, portalOrNpcOnly ? 1 : 0, &found, &d) == 0) return false;
id = found; distance = d;
return true;
}
public double DistanceTo(uint id)
{
var t = Table;
return t == null ? -1 : t->DistanceTo(id);
}
public bool IsPathClear(uint id)
{
var t = Table;
return t == null || t->IsPathClear(id) != 0;
}
/// <summary>A chat line as if typed. Without RynthAi, falls back to AC's own parser.</summary>
public void SubmitCommand(string text)
{
var t = Table;
if (t != null)
{
using var c = new Utf8(text);
if (t->SubmitCommand(c.P) != 0) return;
}
if (_host.HasInvokeChatParser) _host.InvokeChatParser(text);
}
}

View file

@ -0,0 +1,38 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0-windows</TargetFramework>
<PlatformTarget>x86</PlatformTarget>
<RuntimeIdentifier>win-x86</RuntimeIdentifier>
<OutputType>Library</OutputType>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<Nullable>enable</Nullable>
<PublishAot>true</PublishAot>
<NativeLib>Shared</NativeLib>
<InvariantGlobalization>true</InvariantGlobalization>
<IlcOptimizationPreference>Size</IlcOptimizationPreference>
<StripSymbols>false</StripSymbols>
<RootNamespace>RynthCore.Plugin.RynthLua</RootNamespace>
<AssemblyName>RynthCore.Plugin.RynthLua</AssemblyName>
<Platforms>x86</Platforms>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\..\..\RynthCore\src\RynthCore.PluginCore\RynthCore.PluginCore.csproj" />
<ProjectReference Include="..\..\..\RynthCore\src\RynthCore.PluginSdk\RynthCore.PluginSdk.csproj" />
<!-- Lua 5.2 interpreter, pure C#. Its core modules are found by reflection, hence the root. -->
<PackageReference Include="MoonSharp" Version="2.0.0" />
</ItemGroup>
<ItemGroup>
<TrimmerRootAssembly Include="MoonSharp.Interpreter" />
</ItemGroup>
<ItemGroup>
<!-- RynthAi's script interface (RynthAi.Script v1), shared source with RynthAi. -->
<Compile Include="..\Shared\RynthAiScriptApi.cs" Link="Shared\RynthAiScriptApi.cs" />
<!-- One logged, guarded way to use an object (who used what, and why). -->
<Compile Include="..\Shared\UseAudit.cs" Link="Shared\UseAudit.cs" />
</ItemGroup>
</Project>

View file

@ -0,0 +1,23 @@
using System.IO;
namespace RynthCore.Plugin.RynthLua;
/// <summary>
/// Where RynthLua keeps its files. The plugin always uses the defaults; the offline test
/// harness (Tools\RynthLua.CompatTests) points <see cref="Root"/> and
/// <see cref="LegacyScripts"/> at a temporary folder before it loads the plugin, so a test
/// run never touches the real game folders.
/// </summary>
internal static class RynthLuaPaths
{
/// <summary>RynthLua's folder: Scripts\, Data\, settings.json, editor.lua.</summary>
public static string Root { get; set; } = @"C:\Games\RynthSuite\RynthLua";
/// <summary>Where scripts lived while Lua was part of RynthAi (copied over once, then left alone).</summary>
public static string LegacyScripts { get; set; } = @"C:\Games\RynthSuite\RynthAi\LuaScripts";
public static string Scripts => Path.Combine(Root, "Scripts");
public static string Data => Path.Combine(Root, "Data");
public static string Settings => Path.Combine(Root, "settings.json");
public static string Editor => Path.Combine(Root, "editor.lua");
}

View file

@ -0,0 +1,458 @@
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text.Json;
using System.Text.Json.Serialization;
using MoonSharp.Interpreter;
using RynthCore.PluginCore;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthLua;
/// <summary>
/// Panel → plugin Lua command (RynthPluginSendLuaCommand). Cmd: run (Code as Name), stop,
/// clearConsole, load, save, delete (the editor's single-file scripts, as before), and
/// select, start, stopScript, restart, autostart (Code = none|global|character), execin (Code).
/// </summary>
public sealed class LuaCommand
{
public string Cmd { get; set; } = string.Empty;
public string Name { get; set; } = string.Empty;
public string Code { get; set; } = string.Empty;
}
/// <summary>One script in the panel's list.</summary>
public sealed class LuaScriptInfo
{
public string Name { get; set; } = string.Empty;
public bool Running { get; set; }
public string Autostart { get; set; } = "none";
public string Description { get; set; } = string.Empty;
/// <summary>True for a folder script (index.lua), false for a single Name.lua.</summary>
public bool IsFolder { get; set; }
/// <summary>True for a script with no file (the editor, /lua exec): no autostart, restart or load.</summary>
public bool Transient { get; set; }
}
/// <summary>Plugin → panel Lua state (RynthPluginGetLuaJson). Console/Running/ScriptName are the selected script's.</summary>
public sealed class LuaBridgePayload
{
public bool Running { get; set; }
public string ScriptName { get; set; } = string.Empty;
public string Status { get; set; } = string.Empty;
public List<string> Scripts { get; set; } = new();
public string Console { get; set; } = string.Empty;
public int ConsoleSeq { get; set; }
public string LoadedText { get; set; } = string.Empty;
public string LoadedName { get; set; } = string.Empty;
public int LoadSeq { get; set; }
public List<LuaScriptInfo> ScriptInfos { get; set; } = new();
public string Selected { get; set; } = string.Empty;
public int RunningCount { get; set; }
public bool RynthAi { get; set; }
/// <summary>A character is logged in (per-character autostart needs one).</summary>
public bool LoggedIn { get; set; }
}
[JsonSerializable(typeof(LuaCommand))]
[JsonSerializable(typeof(LuaBridgePayload))]
internal partial class RynthLuaJsonContext : JsonSerializerContext { }
/// <summary>
/// RynthLua: Lua scripting for RynthCore (moved out of RynthAi, 2026-09-29). Several scripts
/// run at once, each in its own Lua state, as coroutines on the plugin pump thread
/// (ScriptManager, LuaScriptHost). The API is UtilityBelt-shaped (GameApi and the area
/// files) plus the v1 globals (LuaApi). RynthAi's features come through its "RynthAi.Script"
/// interface (RynthAiBridge). Design: docs/RYNTHLUA.md in RynthSuite.
/// </summary>
public sealed partial class RynthLuaPlugin : RynthPluginBase
{
internal static readonly IntPtr NamePointer = Marshal.StringToHGlobalAnsi("RynthLua");
internal static readonly IntPtr VersionPointer = Marshal.StringToHGlobalAnsi("2.0.0");
private static string DataFolder => RynthLuaPaths.Root;
private static string EditorFile => RynthLuaPaths.Editor;
internal RynthAiBridge _ai = null!;
private readonly ConcurrentQueue<LuaCommand> _panelCommands = new();
private readonly ConcurrentQueue<string> _chatCommands = new(); // "/lua ..." lines, run on the next tick
private string _editorText = string.Empty;
private string _editorName = string.Empty;
private int _loadSeq;
private bool _editorSeeded;
private List<ScriptEntry> _entries = new();
private long _entriesAt;
private bool _examplesChecked;
public override int Initialize()
{
_ai = new RynthAiBridge(Host);
// Every use logged (Plugins/Shared/UseAudit.cs). Scripts are the player's: no guard.
RynthCore.Plugin.Shared.UseAudit.Reset("RynthLua", null);
Log("[RynthLua] Initialized.");
try { LoadResume(); } // a hot reload: the scripts started by hand come back at login
catch (Exception ex) { Log("[RynthLua] resume: " + ex.Message); }
return 0;
}
public override void Shutdown()
{
// The resume list is taken while the scripts still run; the file is written last.
List<string> resume = new();
try { resume = CaptureResume(); } catch { }
try { StopAll("stopped: RynthLua unloaded"); } catch (Exception ex) { Log("[RynthLua] shutdown: " + ex.Message); }
try { ShutdownHuds(); } catch { }
FlushHudMemory();
SaveEditor();
try { WriteResumeFile(ResumeFile, resume, Environment.ProcessId, DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(), s => Log(s)); }
catch { }
}
// ── Tick ────────────────────────────────────────────────────────────────
public override void OnTick()
{
// Plugins now unload on hot reload (collectible load contexts): never keep RynthAi's
// table across ticks, look it up again on first use each tick.
_ai.Reset();
while (_panelCommands.TryDequeue(out var cmd))
{
try { ApplyPanelCommand(cmd); }
catch (Exception ex) { PrintSelected("error: " + ex.Message); }
}
while (_chatCommands.TryDequeue(out string? line))
{
try { HandleLuaChatCommand(line); }
catch (Exception ex) { ChatLine("error: " + ex.Message); }
}
// Script windows are kept apart from the scripts: a fault in the window steps is logged
// (at most every 10 s) and can't stop every script's threads from running.
try { PollHudEvents(); } // script windows: input first, so this tick's passes see it
catch (Exception ex) { LogHudFault("events", ex); }
TickApi();
TickScripts();
try { TickHuds(); } // render passes that are due, then submit what changed
catch (Exception ex) { LogHudFault("passes", ex); }
TickHudMemory(); // the player's hud show/hide choices, written ~2 s after the last one
}
private long _lastHudFaultLog;
private void LogHudFault(string step, Exception ex)
{
if (Environment.TickCount64 - _lastHudFaultLog < 10_000) return;
_lastHudFaultLog = Environment.TickCount64;
Log($"[RynthLua] script windows ({step}): {ex.GetType().Name}: {ex.Message}");
}
// ── Events → scripts (all on the pump thread) ───────────────────────────
/// <summary>v1 on(evt, fn) handlers in every running script.</summary>
private void FireV1(string evt, params DynValue[] args)
{
foreach (var ctx in _scripts.Values.ToArray())
if (ctx.Host.HasHandlers(evt)) ctx.Host.Fire(evt, args);
}
public override void OnLoginComplete()
{
_ai.Reset();
SetGameState("InGame");
WorldOnLogin();
CharacterOnLogin();
FireV1("login");
try { RunAutostart(); }
catch (Exception ex) { Log("[RynthLua] autostart: " + ex.Message); }
try { ResumeScripts(); } // after autostart, so nothing starts twice
catch (Exception ex) { Log("[RynthLua] resume: " + ex.Message); }
}
public override void OnLogout()
{
SetGameState("LoggingOut");
FireV1("logout");
// Global autostart scripts keep running across characters; everything else stops.
StopAll("stopped: logged out", ctx => AutostartOf(ctx.Name) != "global");
ActionsOnLogout();
CharacterOnLogout();
WorldOnLogout();
_ai.Reset();
FlushHudMemory();
SaveEditor();
SetGameState("CharacterSelect");
}
public override void OnChatWindowText(string? text, int chatType, ref int eat)
{
if (string.IsNullOrEmpty(text)) return;
FireV1("chat", DynValue.NewString(text), DynValue.NewNumber(chatType));
WorldOnChatText(text, chatType);
CharacterOnChatText(text, chatType);
ActionsOnChatText(text, chatType);
}
public override void OnSelectedTargetChange(uint currentTargetId, uint previousTargetId)
{
FireV1("target", DynValue.NewNumber(currentTargetId), DynValue.NewNumber(previousTargetId));
WorldOnSelected(currentTargetId, previousTargetId);
}
public override void OnCombatModeChange(int currentCombatMode, int previousCombatMode)
{
FireV1("combatmode", DynValue.NewNumber(currentCombatMode), DynValue.NewNumber(previousCombatMode));
CharacterOnCombatModeChange(currentCombatMode, previousCombatMode);
}
public override void OnCreateObject(uint objectId)
{
FireV1("objectcreated", DynValue.NewNumber(objectId));
WorldOnCreateObject(objectId);
}
public override void OnDeleteObject(uint objectId)
{
FireV1("objectdeleted", DynValue.NewNumber(objectId));
WorldOnDeleteObject(objectId);
}
public override void OnUpdateHealth(uint targetId, float healthRatio, uint currentHealth, uint maxHealth)
{
FireV1("health", DynValue.NewNumber(targetId), DynValue.NewNumber(healthRatio),
DynValue.NewNumber(currentHealth), DynValue.NewNumber(maxHealth));
CharacterOnUpdateHealth(targetId, healthRatio, currentHealth, maxHealth);
}
public override void OnCombatDamage(uint damage, uint damageType, bool crit, bool isAttacker)
=> FireV1(isAttacker ? "damagedealt" : "damagetaken", DynValue.NewNumber(damage), DynValue.NewNumber(damageType), DynValue.NewBoolean(crit));
public override void OnKillNotification(string? deathMessage)
=> FireV1("kill", DynValue.NewString(deathMessage ?? string.Empty));
public override void OnEnchantmentAdded(uint spellId, double durationSeconds)
{
FireV1("enchantmentadded", DynValue.NewNumber(spellId), DynValue.NewNumber(durationSeconds));
CharacterOnEnchantmentAdded(spellId, durationSeconds);
}
public override void OnEnchantmentRemoved(uint enchantmentId)
{
FireV1("enchantmentremoved", DynValue.NewNumber(enchantmentId));
CharacterOnEnchantmentRemoved(enchantmentId);
}
public override void OnVendorOpen(uint vendorId)
{
FireV1("vendoropen", DynValue.NewNumber(vendorId));
WorldOnVendor(vendorId, open: true);
}
public override void OnVendorClose(uint vendorId)
{
FireV1("vendorclose", DynValue.NewNumber(vendorId));
WorldOnVendor(vendorId, open: false);
}
// ── Chat commands ───────────────────────────────────────────────────────
/// <summary>"/lua ..." and script commands typed in chat. AC's thread: only queue for the next tick.</summary>
public override void OnChatBarEnter(string? text, ref int eat)
{
string t = (text ?? string.Empty).Trim();
if (t.Equals("/lua", StringComparison.OrdinalIgnoreCase) || t.StartsWith("/lua ", StringComparison.OrdinalIgnoreCase))
{
_chatCommands.Enqueue(t);
eat = 1;
WorldQueueChatInput(t, alreadyEaten: true);
return;
}
if (t.StartsWith('/') && TryQueueScriptCommand(t)) eat = 1;
// World.OnChatInput (next tick); a command a handler ate before is eaten now.
if (WorldQueueChatInput(t, alreadyEaten: eat != 0)) eat = 1;
}
/// <summary>RynthAi forwards "/ra lua ..." (typed or from a meta) here as ("lua", "run X").</summary>
internal void ApplyRemoteCommand(string action, string value)
{
if (action.Equals("lua", StringComparison.OrdinalIgnoreCase))
_chatCommands.Enqueue("/lua " + value);
}
internal void ChatLine(string text)
{
if (Host.HasWriteToChat) Host.WriteToChat("[RynthLua] " + text, 1);
}
// ── Panel ───────────────────────────────────────────────────────────────
internal void EnqueueLuaCommand(LuaCommand cmd) => _panelCommands.Enqueue(cmd);
private ScriptContext? Selected => _scripts.TryGetValue(_selected, out var c) ? c : null;
private void PrintSelected(string text)
{
var ctx = Selected ?? _scripts.Values.FirstOrDefault();
if (ctx != null) ctx.Host.Print(text);
Log("[RynthLua] " + text);
}
private void ApplyPanelCommand(LuaCommand cmd)
{
switch (cmd.Cmd)
{
case "run":
SetEditor(cmd.Code, cmd.Name, bumpSeq: false);
RunCode(cmd.Name, cmd.Code);
break;
case "stop":
if (Selected != null) StopScript(Selected.Name);
break;
case "clearConsole":
Selected?.Host.ClearConsole();
break;
case "select":
_selected = cmd.Name;
if (!_scripts.ContainsKey(cmd.Name))
{
var e = DiscoverScripts().FirstOrDefault(x => x.Name.Equals(cmd.Name, StringComparison.OrdinalIgnoreCase));
if (e != null) _scripts[e.Name] = NewContext(e.Name, e.Folder, e.EntryFile, e.Manifest, transient: false);
}
break;
case "start":
case "restart":
{
string? err = StartScript(cmd.Name);
if (err != null) PrintSelected(err);
break;
}
case "stopScript":
StopScript(cmd.Name);
break;
case "autostart":
if (cmd.Code == "character" && CharacterKey().Length == 0) { PrintSelected("Log in first to set a script to start for this character."); break; }
SetAutostart(cmd.Name, cmd.Code is "global" or "character" ? cmd.Code : "none");
break;
case "execin":
if (_scripts.TryGetValue(cmd.Name, out var target) && target.Host.Loaded) target.Host.Exec(cmd.Code);
else PrintSelected($"{cmd.Name} isn't running.");
break;
case "load":
{
var e = DiscoverScripts().FirstOrDefault(x => x.Name.Equals(cmd.Name, StringComparison.OrdinalIgnoreCase));
if (e == null) { PrintSelected($"No script named '{cmd.Name}'."); break; }
SetEditor(File.ReadAllText(e.EntryFile), e.Name, bumpSeq: true);
break;
}
case "save":
{
// Folder scripts save their index.lua; everything else a single Name.lua.
var e = DiscoverScripts().FirstOrDefault(x => x.Name.Equals(cmd.Name, StringComparison.OrdinalIgnoreCase));
string? path = e?.EntryFile ?? LuaScriptHost.PathFor(cmd.Name);
if (path == null) { PrintSelected($"'{cmd.Name}' can't be used as a file name."); break; }
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
File.WriteAllText(path, cmd.Code);
SetEditor(cmd.Code, e?.Name ?? Path.GetFileNameWithoutExtension(path), bumpSeq: false);
_entriesAt = 0;
PrintSelected($"Saved {path}.");
break;
}
case "delete":
{
string? path = LuaScriptHost.PathFor(cmd.Name);
if (path == null || !File.Exists(path)) { PrintSelected($"No single-file script named '{cmd.Name}' (folder scripts are deleted in Explorer)."); break; }
// Kept as .bak, not destroyed: a click shouldn't lose someone's script.
string bak = path + ".bak";
if (File.Exists(bak)) File.Delete(bak);
File.Move(path, bak);
_entriesAt = 0;
PrintSelected($"Deleted {Path.GetFileName(path)} (kept as {Path.GetFileName(bak)}).");
break;
}
}
}
private void SetEditor(string text, string name, bool bumpSeq)
{
_editorText = text ?? string.Empty;
_editorName = name ?? string.Empty;
_editorSeeded = true;
if (bumpSeq) _loadSeq++;
SaveEditor();
}
private void SeedEditor()
{
if (_editorSeeded) return;
_editorSeeded = true;
try { if (File.Exists(EditorFile)) _editorText = File.ReadAllText(EditorFile); }
catch { }
if (_editorText.Length == 0) _editorText = "-- Enter your Lua script here\nprint('Hello from RynthLua')";
}
private void SaveEditor()
{
if (!_editorSeeded) return;
try
{
Directory.CreateDirectory(DataFolder);
File.WriteAllText(EditorFile, _editorText);
}
catch { }
}
private void EnsureScripts()
{
if (_examplesChecked) return;
_examplesChecked = true;
LuaExamples.EnsureWritten(s => Log(s));
}
internal string BuildLuaJson()
{
SeedEditor();
long now = Environment.TickCount64;
if (now - _entriesAt > 2000)
{
EnsureScripts();
_entries = DiscoverScripts();
_entriesAt = now;
}
ScriptContext? sel = Selected;
var payload = new LuaBridgePayload
{
Running = sel?.Host.Loaded ?? false,
ScriptName = sel?.Name ?? string.Empty,
Status = sel?.Host.Status ?? string.Empty,
Scripts = _entries.Select(e => e.Name).ToList(),
Console = sel?.Host.ConsoleText() ?? string.Empty,
ConsoleSeq = sel?.Host.ConsoleSeq ?? 0,
LoadedText = _editorText,
LoadedName = _editorName,
LoadSeq = _loadSeq,
Selected = _selected,
RunningCount = _scripts.Values.Count(c => c.Host.Loaded),
RynthAi = _ai.Available,
LoggedIn = CharacterKey().Length > 0,
};
foreach (var e in _entries)
payload.ScriptInfos.Add(new LuaScriptInfo
{
Name = e.Name,
Running = _scripts.TryGetValue(e.Name, out var c) && c.Host.Loaded,
Autostart = AutostartOf(e.Name),
Description = e.Manifest.Description ?? string.Empty,
IsFolder = e.Folder != null,
});
// Scripts that aren't files (the editor, /lua exec) show while running, selected, or
// while they still have console output to read.
foreach (var c in _scripts.Values)
if ((c.Host.Loaded || c.Transient && (c.Host.ConsoleSeq > 0 || c.Name.Equals(_selected, StringComparison.OrdinalIgnoreCase)))
&& !payload.ScriptInfos.Exists(i => i.Name.Equals(c.Name, StringComparison.OrdinalIgnoreCase)))
payload.ScriptInfos.Add(new LuaScriptInfo { Name = c.Name, Running = c.Host.Loaded, Description = "(not saved)", Transient = true });
return JsonSerializer.Serialize(payload, RynthLuaJsonContext.Default.LuaBridgePayload);
}
}

View file

@ -0,0 +1,259 @@
using System;
using System.Collections.Generic;
using System.Text.Json.Serialization;
using MoonSharp.Interpreter;
namespace RynthCore.Plugin.RynthLua;
/// <summary>Optional <c>script.json</c> next to a folder script's <c>index.lua</c>.</summary>
public sealed class ScriptManifest
{
[JsonPropertyName("name")] public string? Name { get; set; }
[JsonPropertyName("description")] public string? Description { get; set; }
[JsonPropertyName("version")] public string? Version { get; set; }
[JsonPropertyName("author")] public string? Author { get; set; }
/// <summary>"none" (the default) | "global" | "character": seeds autostart once; the player can change it.</summary>
[JsonPropertyName("autostart")] public string? Autostart { get; set; }
}
/// <summary>
/// One script: where it lives, its Lua state (<see cref="LuaScriptHost"/>), and everything
/// it registered through the v2 API (events, commands). Stopping the script clears those.
/// </summary>
internal sealed class ScriptContext
{
public string Name { get; }
/// <summary>The script's folder (folder scripts) or null (single-file scripts).</summary>
public string? Folder { get; }
/// <summary>index.lua (folder scripts) or Name.lua.</summary>
public string EntryFile { get; }
public ScriptManifest Manifest { get; }
public LuaScriptHost Host { get; }
/// <summary>True when the script came from the panel editor or /lua exec, not a file.</summary>
public bool Transient { get; init; }
private readonly Dictionary<string, ScriptEvent> _events = new(StringComparer.OrdinalIgnoreCase);
/// <summary>Chat commands this script registered ("/name" → handler).</summary>
public readonly Dictionary<string, DynValue> Commands = new(StringComparer.OrdinalIgnoreCase);
/// <summary>Anything else an API piece wants dropped when the script stops (actions, timers, ...).</summary>
public readonly List<Action> OnStop = new();
/// <summary>Counts of pending work that keeps the script alive (e.g. its queued actions).</summary>
public readonly List<Func<int>> KeepAlive = new();
public ScriptContext(string name, string? folder, string entryFile, ScriptManifest manifest, LuaScriptHost host)
{
Name = name;
Folder = folder;
EntryFile = entryFile;
Manifest = manifest;
Host = host;
host.Folder = folder;
host.ExtraHandlers = () =>
{
int n = Commands.Count;
foreach (var e in _events.Values) n += e.Count;
foreach (var k in KeepAlive)
{
try { n += k(); } catch { }
}
return n;
};
host.Stopped += _ => Clear();
}
/// <summary>The event registered under <paramref name="key"/> (e.g. "World.OnObjectCreated"), created on first use.</summary>
public ScriptEvent Event(string key)
{
if (!_events.TryGetValue(key, out var e)) _events[key] = e = new ScriptEvent(key);
return e;
}
public bool HasHandlers(string key) => _events.TryGetValue(key, out var e) && e.Count > 0;
/// <summary>Keys starting with <paramref name="prefix"/> that have handlers (per-object events).</summary>
public IEnumerable<string> EventKeys(string prefix)
{
foreach (var kv in _events)
if (kv.Value.Count > 0 && kv.Key.StartsWith(prefix, StringComparison.Ordinal)) yield return kv.Key;
}
/// <summary>Forgets an event and its handlers (a per-object event whose object is gone).</summary>
public void DropEvent(string key)
{
if (_events.TryGetValue(key, out var e)) e.Clear();
}
/// <summary>Runs every handler of <paramref name="key"/> with an args table built for this script's Lua state.</summary>
public void Fire(string key, Func<Script, DynValue> makeArgs)
{
if (!Host.Loaded || !_events.TryGetValue(key, out var e) || e.Count == 0) return;
Script? s = Host.Lua;
if (s == null) return;
DynValue args;
try { args = makeArgs(s); }
catch (Exception ex) { Host.Print($"error building {key} args: {ex.Message}"); return; }
e.Fire(Host, args);
}
/// <summary>
/// Calls every handler of <paramref name="key"/> right now, outside coroutines (handlers
/// can't sleep). For events that must run before the Lua state goes away (OnScriptEnd).
/// </summary>
public void FireNow(string key, Func<Script, DynValue> makeArgs)
{
if (!Host.Loaded || !_events.TryGetValue(key, out var e) || e.Count == 0) return;
Script? s = Host.Lua;
if (s == null) return;
DynValue args;
try { args = makeArgs(s); }
catch (Exception ex) { Host.Print($"error building {key} args: {ex.Message}"); return; }
e.CallNow(s, Host, args);
}
private void Clear()
{
_events.Clear();
Commands.Clear();
KeepAlive.Clear();
foreach (Action a in OnStop)
{
try { a(); } catch { }
}
OnStop.Clear();
}
}
/// <summary>
/// A v2 event (UtilityBelt style): a Lua object with <c>Add(fn)</c>, <c>Once(fn)</c>,
/// <c>Until(fn)</c> (kept until the handler returns true) and <c>Remove(fn)</c>. Each handler
/// call runs as its own coroutine, with one args table.
/// </summary>
internal sealed class ScriptEvent
{
private enum Mode { Always, Once }
private readonly List<(DynValue Fn, Mode Mode, DynValue Original)> _handlers = new();
public string Key { get; }
public int Count => _handlers.Count;
public ScriptEvent(string key) => Key = key;
/// <summary>The Lua-side object for this event, in <paramref name="s"/>.</summary>
public DynValue CreateTable(Script s)
{
var t = new Table(s);
DynValue self = DynValue.NewTable(t);
t["Add"] = DynValue.NewCallback((ctx, a) => { Add(LuaArgs.Func(a, t, "Add"), Mode.Always); return DynValue.Nil; });
t["Once"] = DynValue.NewCallback((ctx, a) => { Add(LuaArgs.Func(a, t, "Once"), Mode.Once); return DynValue.Nil; });
t["Until"] = DynValue.NewCallback((ctx, a) =>
{
DynValue fn = LuaArgs.Func(a, t, "Until");
// Wrapped in Lua: the handler's return value is only known once its coroutine
// finishes, so the wrapper removes itself when fn returns true (and skips calls
// for events that were already on their way when it did).
DynValue make = s.LoadString(
"local evt, fn = ...; local w, done; w = function(e) if done then return end; if fn(e) then done = true; evt.Remove(w) end end; return w");
DynValue wrapper = s.Call(make, self, fn);
_handlers.Add((wrapper, Mode.Always, fn));
return DynValue.Nil;
});
t["Remove"] = DynValue.NewCallback((ctx, a) =>
{
DynValue fn = LuaArgs.Func(a, t, "Remove");
_handlers.RemoveAll(h => h.Fn.Equals(fn) || h.Original.Equals(fn));
return DynValue.Nil;
});
// UB's verbs in lower case too (evt.add(fn), evt.once(fn), ...).
t["add"] = t.Get("Add");
t["once"] = t.Get("Once");
t["until"] = t.Get("Until");
t["remove"] = t.Get("Remove");
var mt = new Table(s);
mt["__tostring"] = DynValue.NewCallback((ctx, a) => DynValue.NewString($"Event {Key} ({Count} handler(s))"));
t.MetaTable = mt;
return self;
}
private void Add(DynValue fn, Mode mode) => _handlers.Add((fn, mode, fn));
/// <summary>
/// The handlers, for a caller that runs them itself in one coroutine (a hud's render
/// pass). Once handlers are removed, as <see cref="Fire"/> does.
/// </summary>
public DynValue[] TakeForCall()
{
if (_handlers.Count == 0) return Array.Empty<DynValue>();
var fns = new DynValue[_handlers.Count];
for (int i = 0; i < fns.Length; i++) fns[i] = _handlers[i].Fn;
_handlers.RemoveAll(h => h.Mode == Mode.Once);
return fns;
}
/// <summary>Drops every handler (hud.Dispose).</summary>
public void Clear() => _handlers.Clear();
public void CallNow(Script s, LuaScriptHost host, DynValue args)
{
if (_handlers.Count == 0) return;
var snapshot = _handlers.ToArray();
_handlers.RemoveAll(h => h.Mode == Mode.Once);
foreach (var h in snapshot)
{
try { s.Call(h.Fn, args); }
catch (InterpreterException ex) { host.Print($"{Key}: " + (ex.DecoratedMessage ?? ex.Message)); }
catch (Exception ex) { host.Print($"{Key}: {ex.Message}"); }
}
}
public void Fire(LuaScriptHost host, DynValue args)
{
if (_handlers.Count == 0) return;
var snapshot = _handlers.ToArray();
_handlers.RemoveAll(h => h.Mode == Mode.Once);
foreach (var h in snapshot) host.Start(h.Fn, new[] { args });
}
}
/// <summary>
/// Argument helpers for API callbacks. Methods accept both <c>obj.Method(a)</c> and
/// <c>obj:Method(a)</c>: a leading argument that is the object's own table is dropped.
/// </summary>
internal static class LuaArgs
{
public static DynValue[] Of(CallbackArguments a, Table? self)
{
int start = self != null && a.Count > 0 && a[0].Type == DataType.Table && ReferenceEquals(a[0].Table, self) ? 1 : 0;
var r = new DynValue[Math.Max(0, a.Count - start)];
for (int i = start; i < a.Count; i++) r[i - start] = a[i];
return r;
}
public static DynValue At(DynValue[] args, int i) => i < args.Length ? args[i] : DynValue.Nil;
public static DynValue Func(CallbackArguments a, Table self, string what)
{
DynValue fn = At(Of(a, self), 0);
if (fn.Type != DataType.Function && fn.Type != DataType.ClrFunction)
throw new ScriptRuntimeException($"{what}(function) needs a function");
return fn;
}
public static string Str(DynValue v, string fallback = "") => v.IsNil() ? fallback : v.CastToString() ?? fallback;
public static double Num(DynValue v, double fallback = 0) =>
v.Type == DataType.Number ? v.Number
: LuaEnumValues.TryRead(v, out _, out long typed) ? typed
: double.TryParse(v.CastToString(), System.Globalization.NumberStyles.Float,
System.Globalization.CultureInfo.InvariantCulture, out double d) ? d : fallback;
public static uint Id(DynValue v)
{
if (v.Type == DataType.Number) return (uint)v.Number;
if (v.Type == DataType.Table)
{
DynValue id = v.Table.Get("Id");
if (id.Type == DataType.Number) return (uint)id.Number;
}
return 0;
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,328 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace RynthCore.Plugin.RynthLua;
/// <summary>RynthLua's own settings (C:\Games\RynthSuite\RynthLua\settings.json).</summary>
public sealed class LuaSettings
{
/// <summary>Scripts that start on every character's login.</summary>
public List<string> GlobalScripts { get; set; } = new();
/// <summary>"server|character" → scripts that start on that character's login.</summary>
public Dictionary<string, List<string>> CharacterScripts { get; set; } = new();
/// <summary>Scripts whose manifest autostart was applied once (so turning it off sticks).</summary>
public List<string> SeededFromManifest { get; set; } = new();
}
[JsonSerializable(typeof(ScriptManifest))]
[JsonSerializable(typeof(LuaSettings))]
internal partial class RynthLuaSettingsJsonContext : JsonSerializerContext { }
/// <summary>A script the panel and /lua list can show.</summary>
internal sealed record ScriptEntry(string Name, string? Folder, string EntryFile, ScriptManifest Manifest);
/// <summary>
/// Scripts: discovery (folder scripts with index.lua, single-file Name.lua), start / stop /
/// restart, several at once, autostart, the shared tick budget and the /lua commands.
/// </summary>
public sealed partial class RynthLuaPlugin
{
private static string SettingsFile => RynthLuaPaths.Settings;
// CPU per game tick across every script. Stopwatch, not TickCount64: that clock
// moves in ~15.6 ms steps, which let a busy loop take a whole step.
private static readonly long TickBudgetTicks = System.Diagnostics.Stopwatch.Frequency * 4 / 1000;
private readonly Dictionary<string, ScriptContext> _scripts = new(StringComparer.OrdinalIgnoreCase);
private int _tickRotation;
private LuaSettings _settings = new();
private bool _settingsLoaded;
/// <summary>The script the panel shows (its console, and the editor's run target).</summary>
private string _selected = string.Empty;
// ── Discovery ───────────────────────────────────────────────────────────
internal static List<ScriptEntry> DiscoverScripts()
{
var list = new List<ScriptEntry>();
try
{
if (!Directory.Exists(LuaScriptHost.ScriptFolder)) return list;
foreach (string dir in Directory.GetDirectories(LuaScriptHost.ScriptFolder))
{
string index = Path.Combine(dir, "index.lua");
if (!File.Exists(index)) continue;
string name = Path.GetFileName(dir);
list.Add(new ScriptEntry(name, dir, index, ReadManifest(dir)));
}
foreach (string f in Directory.GetFiles(LuaScriptHost.ScriptFolder, "*.lua"))
{
string name = Path.GetFileNameWithoutExtension(f);
if (list.Exists(e => e.Name.Equals(name, StringComparison.OrdinalIgnoreCase))) continue;
list.Add(new ScriptEntry(name, null, f, new ScriptManifest()));
}
}
catch { }
list.Sort((a, b) => string.Compare(a.Name, b.Name, StringComparison.OrdinalIgnoreCase));
return list;
}
private static ScriptManifest ReadManifest(string dir)
{
try
{
string file = Path.Combine(dir, "script.json");
if (File.Exists(file))
return JsonSerializer.Deserialize(File.ReadAllText(file), RynthLuaSettingsJsonContext.Default.ScriptManifest) ?? new ScriptManifest();
}
catch { }
return new ScriptManifest();
}
private static ScriptEntry? FindScript(string name)
{
string n = (name ?? string.Empty).Trim();
if (n.EndsWith(".lua", StringComparison.OrdinalIgnoreCase)) n = n[..^4].TrimEnd();
return DiscoverScripts().FirstOrDefault(e => e.Name.Equals(n, StringComparison.OrdinalIgnoreCase));
}
// ── Start / stop ────────────────────────────────────────────────────────
private ScriptContext NewContext(string name, string? folder, string entry, ScriptManifest manifest, bool transient)
{
ScriptContext? ctx = null;
var host = new LuaScriptHost(s => Log(s), (s, h) => RegisterApi(s, h, ctx!))
{
MacroRunning = () => _ai.MacroRunning,
};
ctx = new ScriptContext(name, folder, entry, manifest, host) { Transient = transient };
host.ResolveModule = (s, module) => ResolveModule(s, ctx, module);
return ctx;
}
/// <summary>Starts (or restarts) a script from its file. Returns an error message, or null.</summary>
internal string? StartScript(string name)
{
ScriptEntry? e = FindScript(name);
if (e == null) return $"No script named '{name}'. /lua list shows them.";
string code;
try { code = File.ReadAllText(e.EntryFile); }
catch (Exception ex) { return $"Can't read {e.EntryFile}: {ex.Message}"; }
StopScript(e.Name, "restarted");
var ctx = NewContext(e.Name, e.Folder, e.EntryFile, e.Manifest, transient: false);
_scripts[e.Name] = ctx;
_selected = e.Name;
ctx.Host.Run(code, e.Name);
return ctx.Host.Loaded ? null : $"{e.Name} failed to start; see its console in the Lua panel.";
}
/// <summary>Runs code as a script called <paramref name="name"/> (panel editor, /lua exec).</summary>
internal ScriptContext RunCode(string name, string code)
{
string n = string.IsNullOrWhiteSpace(name) ? "editor" : name.Trim();
StopScript(n, "replaced by a new run");
ScriptEntry? e = FindScript(n);
var ctx = NewContext(n, e?.Folder, e?.EntryFile ?? string.Empty, e?.Manifest ?? new ScriptManifest(), transient: true);
_scripts[n] = ctx;
_selected = n;
ctx.Host.Run(code, n);
return ctx;
}
internal bool StopScript(string name, string reason = "stopped")
{
if (!_scripts.TryGetValue(name, out var ctx) || !ctx.Host.Loaded) return false;
FireScriptEnd(ctx);
ctx.Host.Stop(reason);
return true;
}
internal void StopAll(string reason, Func<ScriptContext, bool>? which = null)
{
foreach (var ctx in _scripts.Values.ToArray())
if (ctx.Host.Loaded && (which == null || which(ctx)))
{
FireScriptEnd(ctx);
ctx.Host.Stop(reason);
}
}
internal IEnumerable<ScriptContext> RunningScripts() => _scripts.Values.Where(c => c.Host.Loaded);
// ── Tick ────────────────────────────────────────────────────────────────
private void TickScripts()
{
if (_scripts.Count == 0) return;
long deadline = System.Diagnostics.Stopwatch.GetTimestamp() + TickBudgetTicks;
var list = _scripts.Values.Where(c => c.Host.Loaded).ToList();
if (list.Count == 0) return;
int start = _tickRotation++ % list.Count;
for (int k = 0; k < list.Count; k++)
{
if (System.Diagnostics.Stopwatch.GetTimestamp() >= deadline) break;
var ctx = list[(start + k) % list.Count];
try { ctx.Host.Tick(deadline); }
catch (Exception ex) { ctx.Host.Print("error: " + ex.Message); }
}
}
// ── Autostart ───────────────────────────────────────────────────────────
private void LoadSettings()
{
if (_settingsLoaded) return;
_settingsLoaded = true;
try
{
if (File.Exists(SettingsFile))
_settings = JsonSerializer.Deserialize(File.ReadAllText(SettingsFile), RynthLuaSettingsJsonContext.Default.LuaSettings) ?? new LuaSettings();
}
catch { _settings = new LuaSettings(); }
}
private void SaveSettings()
{
try
{
Directory.CreateDirectory(Path.GetDirectoryName(SettingsFile)!);
File.WriteAllText(SettingsFile, JsonSerializer.Serialize(_settings, RynthLuaSettingsJsonContext.Default.LuaSettings));
}
catch { }
}
/// <summary>"server|character" for the logged-in character, or "" before login.</summary>
internal string CharacterKey()
{
uint id = Host.GetPlayerId();
string ch = id != 0 && Host.TryGetObjectName(id, out string n) ? n : string.Empty;
string server = Host.TryGetWorldName(out string w) ? w : string.Empty;
return ch.Length == 0 ? string.Empty : $"{server}|{ch}";
}
/// <summary>"global", "character" or "none" for this script and character.</summary>
internal string AutostartOf(string name)
{
LoadSettings();
if (_settings.GlobalScripts.Contains(name, StringComparer.OrdinalIgnoreCase)) return "global";
string key = CharacterKey();
if (key.Length > 0 && _settings.CharacterScripts.TryGetValue(key, out var l) && l.Contains(name, StringComparer.OrdinalIgnoreCase))
return "character";
return "none";
}
internal void SetAutostart(string name, string mode)
{
LoadSettings();
string key = CharacterKey();
_settings.GlobalScripts.RemoveAll(n => n.Equals(name, StringComparison.OrdinalIgnoreCase));
if (key.Length > 0 && _settings.CharacterScripts.TryGetValue(key, out var l))
l.RemoveAll(n => n.Equals(name, StringComparison.OrdinalIgnoreCase));
if (mode == "global") _settings.GlobalScripts.Add(name);
else if (mode == "character" && key.Length > 0)
{
if (!_settings.CharacterScripts.TryGetValue(key, out var list)) _settings.CharacterScripts[key] = list = new List<string>();
list.Add(name);
}
if (!_settings.SeededFromManifest.Contains(name, StringComparer.OrdinalIgnoreCase)) _settings.SeededFromManifest.Add(name);
SaveSettings();
}
/// <summary>On login: seed autostart from manifests (once per script), then start what's set.</summary>
private void RunAutostart()
{
LoadSettings();
var all = DiscoverScripts();
foreach (var e in all)
{
if (_settings.SeededFromManifest.Contains(e.Name, StringComparer.OrdinalIgnoreCase)) continue;
string m = (e.Manifest.Autostart ?? "none").Trim().ToLowerInvariant();
if (m is "global" or "character") SetAutostart(e.Name, m);
}
foreach (var e in all)
{
string mode = AutostartOf(e.Name);
if (mode == "none") continue;
if (_scripts.TryGetValue(e.Name, out var running) && running.Host.Loaded) continue; // global ones keep running across logins
string? err = StartScript(e.Name);
Log(err == null ? $"[RynthLua] Autostarted {e.Name} ({mode})." : $"[RynthLua] Autostart {e.Name}: {err}");
}
}
// ── /lua commands ───────────────────────────────────────────────────────
private void HandleLuaChatCommand(string line)
{
string[] parts = line.Split(' ', 3, StringSplitOptions.RemoveEmptyEntries);
string sub = parts.Length > 1 ? parts[1].ToLowerInvariant() : "";
string rest = parts.Length > 2 ? parts[2].Trim() : "";
switch (sub)
{
case "run":
case "start":
{
string? err = StartScript(rest);
ChatLine(err ?? $"Running {FindScript(rest)?.Name ?? rest}.");
break;
}
case "restart":
{
string? err = StartScript(rest);
ChatLine(err ?? $"Restarted {FindScript(rest)?.Name ?? rest}.");
break;
}
case "stop":
if (rest.Length == 0 || rest.Equals("all", StringComparison.OrdinalIgnoreCase))
{
int n = RunningScripts().Count();
StopAll("stopped");
ChatLine(n == 0 ? "No script is running." : $"Stopped {n} script(s).");
}
else ChatLine(StopScript(FindScript(rest)?.Name ?? rest) ? $"Stopped {rest}." : $"{rest} isn't running.");
break;
case "exec":
if (rest.Length == 0) { ChatLine("Usage: /lua exec <code>"); break; }
RunCode("exec", rest);
break;
case "execin":
{
string[] p = rest.Split(' ', 2, StringSplitOptions.RemoveEmptyEntries);
if (p.Length < 2) { ChatLine("Usage: /lua execin <script> <code>"); break; }
if (!_scripts.TryGetValue(p[0], out var ctx) || !ctx.Host.Loaded) { ChatLine($"{p[0]} isn't running."); break; }
ctx.Host.Exec(p[1]);
break;
}
case "autostart":
{
string[] p = rest.Split(' ', 2, StringSplitOptions.RemoveEmptyEntries);
string mode = p.Length > 1 ? p[1].ToLowerInvariant() : "";
var e = p.Length > 0 ? FindScript(p[0]) : null;
if (e == null || mode is not ("none" or "global" or "character"))
{ ChatLine("Usage: /lua autostart <script> none|global|character"); break; }
SetAutostart(e.Name, mode);
ChatLine($"{e.Name}: autostart {mode}.");
break;
}
case "list":
{
EnsureScripts();
var all = DiscoverScripts();
if (all.Count == 0) { ChatLine($"No scripts in {LuaScriptHost.ScriptFolder}."); break; }
ChatLine($"Scripts ({all.Count}): " + string.Join(", ", all.Select(e =>
e.Name + (_scripts.TryGetValue(e.Name, out var c) && c.Host.Loaded ? " [running]" : "")
+ (AutostartOf(e.Name) is var a && a != "none" ? $" [auto:{a}]" : ""))));
break;
}
case "hud":
HandleHudCommand(rest);
break;
default:
ChatLine("/lua list | start <script> | stop <script>|all | restart <script> | exec <code> | execin <script> <code> | autostart <script> none|global|character | hud list|show|hide|toggle <script>/<hud>|bench <n>|bench off");
break;
}
}
}

View file

@ -0,0 +1,180 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.Json;
namespace RynthCore.Plugin.RynthLua;
/// <summary>
/// Resume after a hot reload (design doc §8 decision 3). Shutdown writes resume.json with the
/// scripts the player started by hand (from a file, no autostart); the next Initialize keeps
/// that list only when the file comes from this same process and is under 60 s old, which
/// means a reload, not a new client; OnLoginComplete starts them after autostart.
/// Utf8JsonWriter / JsonDocument only (no serialized types), every file step in try/catch.
/// </summary>
public sealed partial class RynthLuaPlugin
{
private const long ResumeMaxAgeMs = 60_000;
/// <summary>How long after Initialize the list waits for a login. A reload at character select
/// doesn't start the scripts on whichever character logs in minutes later.</summary>
private const long ResumeWaitMs = 120_000;
private const int ResumeMaxScripts = 100;
private List<string>? _resumePending;
private long _resumePendingAt;
/// <summary>Offline tests only: stands in for DataFolder\resume.json when set.</summary>
private string? ResumeFileOverride { get; set; }
private string ResumeFile => ResumeFileOverride ?? Path.Combine(DataFolder, "resume.json");
// ── Shutdown ────────────────────────────────────────────────────────────
/// <summary>Before StopAll: the running scripts to bring back after the reload.</summary>
private List<string> CaptureResume()
=> ResumeCandidates(_scripts.Values, name =>
{
try { return AutostartOf(name); }
catch { return "none"; } // login skips anything already running, so no double start
});
/// <summary>Running, from a file (not the editor or /lua exec), and not autostart (those restart on their own).</summary>
internal static List<string> ResumeCandidates(IEnumerable<ScriptContext> scripts, Func<string, string> autostartOf)
{
var list = new List<string>();
foreach (ScriptContext ctx in scripts)
{
if (!ctx.Host.Loaded || ctx.Transient) continue;
if (autostartOf(ctx.Name) != "none") continue;
if (list.Exists(n => n.Equals(ctx.Name, StringComparison.OrdinalIgnoreCase))) continue;
list.Add(ctx.Name);
if (list.Count >= ResumeMaxScripts) break;
}
return list;
}
/// <summary>{"pid": n, "savedAtUtcMs": n, "scripts": [...]}, written even when empty so an older file can't bring scripts back.</summary>
internal static bool WriteResumeFile(string path, IReadOnlyList<string> names, int pid, long savedAtUtcMs, Action<string> log)
{
string tmp = path + ".tmp";
try
{
string? dir = Path.GetDirectoryName(path);
if (!string.IsNullOrEmpty(dir)) Directory.CreateDirectory(dir);
using (var stream = new FileStream(tmp, FileMode.Create, FileAccess.Write, FileShare.None))
using (var w = new Utf8JsonWriter(stream, new JsonWriterOptions { Indented = true }))
{
w.WriteStartObject();
w.WriteNumber("pid", pid);
w.WriteNumber("savedAtUtcMs", savedAtUtcMs);
w.WriteStartArray("scripts");
foreach (string n in names) w.WriteStringValue(n);
w.WriteEndArray();
w.WriteEndObject();
}
File.Move(tmp, path, overwrite: true);
return true;
}
catch (Exception ex)
{
log("[RynthLua] can't write resume.json: " + ex.Message);
try { if (File.Exists(tmp)) File.Delete(tmp); } catch { }
return false;
}
}
/// <summary>
/// Reads and deletes the file. Returns the scripts when it is from process <paramref name="pid"/>
/// and 0-60 s old, otherwise null (a new client, a stale or bad file, or no file).
/// </summary>
internal static List<string>? ReadResumeFile(string path, int pid, long nowUtcMs, Action<string> log)
{
byte[] bytes;
try
{
if (!File.Exists(path)) return null;
bytes = File.ReadAllBytes(path);
}
catch { return null; }
finally
{
try { if (File.Exists(path)) File.Delete(path); } catch { }
}
try
{
using JsonDocument doc = JsonDocument.Parse(bytes);
JsonElement root = doc.RootElement;
if (root.ValueKind != JsonValueKind.Object) return null;
if (!root.TryGetProperty("pid", out JsonElement p) || p.ValueKind != JsonValueKind.Number || !p.TryGetInt32(out int filePid) || filePid != pid)
return null;
if (!root.TryGetProperty("savedAtUtcMs", out JsonElement t) || t.ValueKind != JsonValueKind.Number || !t.TryGetInt64(out long savedAt))
return null;
long age = nowUtcMs - savedAt;
if (age < 0 || age > ResumeMaxAgeMs) return null;
if (!root.TryGetProperty("scripts", out JsonElement arr) || arr.ValueKind != JsonValueKind.Array) return null;
var list = new List<string>();
foreach (JsonElement e in arr.EnumerateArray())
{
if (e.ValueKind != JsonValueKind.String) continue;
string n = (e.GetString() ?? string.Empty).Trim();
if (n.Length == 0 || list.Exists(x => x.Equals(n, StringComparison.OrdinalIgnoreCase))) continue;
list.Add(n);
if (list.Count >= ResumeMaxScripts) break;
}
return list;
}
catch (Exception ex)
{
log("[RynthLua] ignoring a bad resume.json: " + ex.Message);
return null;
}
}
// ── Initialize ──────────────────────────────────────────────────────────
private void LoadResume()
{
List<string>? list = ReadResumeFile(ResumeFile, Environment.ProcessId, DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(), s => Log(s));
if (list == null || list.Count == 0) return;
_resumePending = list;
_resumePendingAt = Environment.TickCount64;
Log($"[RynthLua] resuming {list.Count} script(s) after a reload");
}
// ── OnLoginComplete (after RunAutostart) ────────────────────────────────
private void ResumeScripts()
{
List<string>? list = _resumePending;
_resumePending = null;
if (list == null || list.Count == 0) return;
if (Environment.TickCount64 - _resumePendingAt > ResumeWaitMs)
{
Log($"[RynthLua] not resuming {list.Count} script(s): the login came too long after the reload");
return;
}
RunResume(list, name => _scripts.TryGetValue(name, out var c) && c.Host.Loaded, StartScript, s => Log(s));
}
/// <summary>Starts each script that isn't already running, each on its own. Returns how many started.</summary>
internal static int RunResume(IReadOnlyList<string> names, Func<string, bool> isRunning, Func<string, string?> start, Action<string> log)
{
int started = 0;
foreach (string name in names)
{
try
{
if (isRunning(name)) continue; // autostart (or something else) already brought it back
string? err = start(name);
if (err == null) started++;
log(err == null ? $"[RynthLua] Resumed {name}." : $"[RynthLua] Resume {name}: {err}");
}
catch (Exception ex)
{
log($"[RynthLua] Resume {name}: {ex.Message}");
}
}
return started;
}
}

View file

@ -0,0 +1,885 @@
using System;
using System.Buffers.Binary;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Text;
using MoonSharp.Interpreter;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthLua;
/// <summary>
/// Script windows (engine API v71), Phase 0: the huds of every running script, their render
/// passes and the round trip with the engine. Each tick, on the pump thread:
/// 1. UiPollEvents: clicks and checkbox values go to their hud (applied by its next pass);
/// 2. (scripts run: TickScripts);
/// 3. render passes for the huds that are due, in their own 1.5 ms slice;
/// 4. UiSubmit when any hud's list or properties changed.
/// Lua never runs on AC's thread: OnRender records a display list the engine replays every
/// frame. Design: Docs/RYNTHLUA_WINDOWS_DESIGN.md.
/// </summary>
public sealed partial class RynthLuaPlugin
{
private const int HudsPerScript = 8;
private const int HudsPerPlugin = 32;
internal const int DefaultRefreshRate = 20; // decision 5: passes per second while visible
internal const int MinRefreshRate = 1, MaxRefreshRate = 60;
private const int PassInstructionCap = 200_000; // §6.1
private const int HudErrorStrikes = 20;
private const int MaxHudErrorChars = 2000;
private static readonly long PassSliceTicks = Stopwatch.Frequency * 15 / 10_000; // 1.5 ms
private long _lastSlowLogAt;
private static readonly long StatsEveryTicks = Stopwatch.Frequency * 10;
private readonly List<ScriptHud> _huds = new();
private readonly Dictionary<uint, ScriptHud> _hudsByHash = new();
private readonly HudRecorder _recorder = new();
private bool _hudSetChanged;
private bool _hudsEverSubmitted;
private uint _lastPolledSeq;
private byte[] _submitBuffer = new byte[4096];
private byte[] _eventBuffer = new byte[8192];
private int _hudRotation;
private int _submitRotation;
private long _submitRetryAt;
private long _lastSubmitErrorLog;
// Engine facts (UiGetInfo), refreshed about once a second.
private bool _uiAvailable;
private long _uiInfoAt;
private int _maxOps = 1500, _maxBytes = 64 * 1024, _maxSubmitBytes = HudFormat.DefaultMaxSubmitBytes;
// Phase 0 measurements (logged about every 10 s while a hud is visible).
private long _statsStart;
private int _statPasses, _statAborts, _statSubmits, _statMaxOps;
private long _statPassTicks, _statPassMax, _statOps, _statSubmitBytes, _statSubmitTicks;
// ── Availability ────────────────────────────────────────────────────────
/// <summary>views.Available: the engine has API v71 and ImGui is on.</summary>
internal bool UiAvailable
{
get
{
RefreshUiInfo(force: false);
return _uiAvailable;
}
}
/// <summary>Refreshes views.Available, the limits and the query metrics from UiGetInfo (at most once a second unless forced).</summary>
private void RefreshUiInfo(bool force)
{
long now = Stopwatch.GetTimestamp();
if (!force && _uiInfoAt != 0 && now - _uiInfoAt < Stopwatch.Frequency) return;
_uiInfoAt = now;
if (!Host.HasUi) { _uiAvailable = false; return; }
bool got = Host.TryGetUiInfo(out UiInfoNative info);
_uiAvailable = got && (info.Flags & 1) != 0;
// OpLevel was a reserved 0 before 2026-09-30: those engines replay the Phase 1 ops only.
if (got) _uiOpLevel = Math.Max((int)info.OpLevel, 1);
if (info.MaxOpsPerWindow > 0) _maxOps = (int)Math.Min(info.MaxOpsPerWindow, 1500);
if (info.MaxBytesPerWindow > 0) _maxBytes = (int)Math.Min(info.MaxBytesPerWindow, 64 * 1024);
if (info.MaxBytesPerSubmit > 0) _maxSubmitBytes = (int)Math.Min(info.MaxBytesPerSubmit, (uint)HudFormat.DefaultMaxSubmitBytes);
// The engine fills the metrics once its ImGui frame has run; until then they are 0.
if (got && float.IsFinite(info.TextLineHeight) && info.TextLineHeight > 0) CopyUiMetrics(info);
}
// UiGetInfo's metrics for the queries (GetTextLineHeight, CalcTextSize, ...), in logical units
// (pixels / UiScale), the units of widget sizes and geometry. Defaults until the engine reports them.
private float _uiScale = 1f;
private float _uiLineHeight = 14f, _uiFrameHeight = 20f;
private float _uiSpacingX = 8f, _uiSpacingY = 4f, _uiPaddingX = 4f, _uiPaddingY = 3f;
/// <summary>Default-font advance of ' '..'~', PIXELS at <see cref="_uiScale"/> (CalcTextSize rounds in pixels as ImGui does).</summary>
private readonly float[] _uiAdvancePx = DefaultAdvances();
private static float[] DefaultAdvances()
{
var a = new float[95];
Array.Fill(a, 7f);
return a;
}
private unsafe void CopyUiMetrics(UiInfoNative info)
{
float scale = float.IsFinite(info.UiScale) && info.UiScale > 0 ? info.UiScale : 1f;
static float Ok(float v, float fallback) => float.IsFinite(v) && v >= 0 ? v : fallback;
_uiScale = scale;
_uiLineHeight = Ok(info.TextLineHeight, 14f * scale) / scale;
_uiFrameHeight = Ok(info.FrameHeight, 20f * scale) / scale;
_uiSpacingX = Ok(info.ItemSpacingX, 8f * scale) / scale;
_uiSpacingY = Ok(info.ItemSpacingY, 4f * scale) / scale;
_uiPaddingX = Ok(info.FramePaddingX, 4f * scale) / scale;
_uiPaddingY = Ok(info.FramePaddingY, 3f * scale) / scale;
for (int i = 0; i < 95; i++) _uiAdvancePx[i] = Ok(info.AsciiAdvance[i], 7f * scale);
}
// ── Huds (the views module calls these) ─────────────────────────────────
internal ScriptHud CreateHud(ScriptContext ctx, string name)
{
foreach (ScriptHud h in _huds)
if (h.Ctx == ctx && h.Name == name && !h.Disposed) return h; // UB: same name, same hud
if (_huds.Count(h => h.Ctx == ctx) >= HudsPerScript)
throw new ScriptRuntimeException($"a script can have at most {HudsPerScript} huds");
if (_huds.Count >= HudsPerPlugin)
throw new ScriptRuntimeException($"RynthLua can show at most {HudsPerPlugin} huds at once");
string key = WindowKey(ctx.Name, name);
var hud = new ScriptHud(ctx, name, key,
ctx.Event($"Hud:{name}:OnRender"), ctx.Event($"Hud:{name}:OnPreRender"));
if (_hudsByHash.ContainsKey(hud.Hash))
throw new ScriptRuntimeException($"CreateHud(\"{name}\"): the name clashes with another hud; pick another name");
// The engine's panel key (saved placement, the bar, /rc ui) ignores case and turns
// control characters into spaces and '=', ',' and '#' into '_'; it refuses a second
// window on the same panel key, on every submit.
string panelKey = PanelKeyOf(key);
foreach (ScriptHud h in _huds)
if (!h.Disposed && string.Equals(PanelKeyOf(h.Key), panelKey, StringComparison.OrdinalIgnoreCase))
throw new ScriptRuntimeException(
$"CreateHud(\"{name}\"): the name clashes with hud \"{h.Name}\"{(h.Ctx == ctx ? "" : $" of {h.Ctx.Name}")} (hud names ignore case, and '=', ',' and '#' count as '_'); pick another name");
// Initial visibility (§1.2, decision 9): the player's last choice for this window on
// this character, else hidden. Before login there is no character, so hidden. The
// memory applies only here, at CreateHud: the huds of a global script that keeps
// running across a character change are not re-applied for the new character (the
// script's own hud.Visible, or the player, decides from there).
string character = HudCharacter();
if (character.Length > 0 && HudMemory.TryGet(character, key, out bool remembered) && remembered)
{
hud.Visible = true;
hud.PassNow = true;
hud.FirstPassSinceShown = true;
}
if (!_huds.Any(h => h.Ctx == ctx))
ctx.OnStop.Add(() => RemoveHudsOf(ctx));
_huds.Add(hud);
_hudsByHash[hud.Hash] = hud;
_hudSetChanged = true;
if (!UiAvailable && _uiWarned.Add(ctx.Name))
ctx.Host.Print("script windows need RynthCore API v71 or later with ImGui on; this hud won't show");
return hud;
}
private readonly HashSet<string> _uiWarned = new(StringComparer.OrdinalIgnoreCase);
// ── Per-character visibility memory (decision 9) ────────────────────────
private HudVisibilityMemory? _hudMemory;
/// <summary>Offline tests only: stands in for <see cref="CharacterKey"/> when set.</summary>
private string? HudCharacterOverride { get; set; }
private HudVisibilityMemory HudMemory =>
_hudMemory ??= new HudVisibilityMemory(System.IO.Path.Combine(DataFolder, "hud_visibility.json"), s => Log(s));
/// <summary>"server|character", or "" before login (nothing is remembered or recalled then).</summary>
private string HudCharacter()
{
if (HudCharacterOverride != null) return HudCharacterOverride;
try { return CharacterKey(); }
catch { return string.Empty; }
}
/// <summary>OnTick: writes the memory ~2 s after the player's last change.</summary>
private void TickHudMemory()
{
try { _hudMemory?.Tick(Environment.TickCount64); }
catch { }
}
/// <summary>Logout and shutdown: writes pending changes now.</summary>
private void FlushHudMemory()
{
try { _hudMemory?.Flush(); }
catch { }
}
/// <summary>A window key as the engine's panel key sees it (compare case-insensitively).</summary>
internal static string PanelKeyOf(string key)
{
var sb = new StringBuilder(key.Length);
foreach (char c in key)
sb.Append(char.IsControl(c) ? ' ' : c is '=' or ',' or '#' ? '_' : c);
return sb.ToString();
}
/// <summary>"RynthLua/&lt;script&gt;/&lt;hud&gt;", at most 128 UTF-8 bytes.</summary>
private static string WindowKey(string script, string hud)
{
string key = $"RynthLua/{script}/{hud}";
while (Encoding.UTF8.GetByteCount(key) > HudFormat.MaxStr8) key = key[..^1];
return key;
}
/// <summary>
/// Shows or hides a hud, whoever asked: the script (hud.Visible), the player (the X, the
/// bar; through <see cref="OnPlayerVisibility"/>) or /lua hud. On an actual change it fires
/// OnShow / OnHide (queued as script threads, never run inline, so a handler can sleep and
/// can't re-enter this call). The flag goes to the engine with the next submit.
/// </summary>
internal void SetHudVisible(ScriptHud hud, bool visible)
{
if (hud.Visible == visible || hud.Disposed) return;
hud.Visible = visible;
hud.PropsDirty = true;
if (visible)
{
hud.PassNow = true;
hud.FirstPassSinceShown = true;
hud.ErrorStreak = 0; // hidden and shown again: a hud stopped after 20 errors tries again
}
else
{
// A hidden hud runs no pass: its clicks and values are dropped, so they neither fire
// when it comes back nor hold every window's AckSeq back meanwhile.
hud.DropPendingInput();
}
try { hud.Ctx.Fire((visible ? hud.OnShow : hud.OnHide).Key, s => DynValue.NewTable(new Table(s))); }
catch (Exception ex) { hud.Ctx.Host.Print($"hud {hud.Name}: {(visible ? "OnShow" : "OnHide")}: {ex.Message}"); }
}
/// <summary>
/// The player showed or hid the window (reason 1: the X or /rc ui close; 2: the bar's
/// Scripts menu or /rc ui open). hud.Visible follows (OnShow/OnHide fire), the choice is
/// remembered for this character, and the next submit carries the flag with an AckSeq that
/// covers the event, so the engine takes the flag again (it ignores older ones).
/// </summary>
internal void OnPlayerVisibility(ScriptHud hud, bool visible, byte reason)
{
if (hud.Disposed) return;
SetHudVisible(hud, visible);
hud.PropsDirty = true; // the next submit's flag agrees with the player even when nothing changed here
if (reason is VisibilityPlayerClose or VisibilityBarOrCommand) RememberPlayerChoice(hud, visible);
}
/// <summary>/lua hud show|hide|toggle: the same as the player doing it (remembered; OnShow/OnHide fire).</summary>
internal void PlayerSetHudVisible(ScriptHud hud, bool visible)
{
if (hud.Disposed) return;
SetHudVisible(hud, visible);
RememberPlayerChoice(hud, visible);
}
private const byte VisibilityPlayerClose = 1, VisibilityBarOrCommand = 2; // the engine's reason codes
private void RememberPlayerChoice(ScriptHud hud, bool visible)
{
try { HudMemory.Record(HudCharacter(), hud.Key, visible, Environment.TickCount64); }
catch { }
}
internal void SetHudTitle(ScriptHud hud, string title)
{
if (hud.Title == title) return;
hud.Title = title;
hud.PropsDirty = true;
hud.PassNow = true;
}
// ImGuiWindowFlags (ImGui 1.91.6) for hud.WindowSettings.
private const long WsNoTitleBar = 1, WsNoScrollbar = 8, WsNoScrollWithMouse = 16, WsNoCollapse = 32,
WsNoBackground = 128, WsNoMouseInputs = 512, WsNoNavInputs = 1 << 16, WsNoNavFocus = 1 << 17;
/// <summary>Accepted without a warning: NoInputs' nav bits (keyboard nav doesn't reach script windows) and NoCollapse (the RynthCore frame never collapses).</summary>
private const long WsQuiet = WsNoNavInputs | WsNoNavFocus | WsNoCollapse;
private const long WsHonoured = WsNoTitleBar | WsNoScrollbar | WsNoScrollWithMouse | WsNoBackground | WsNoMouseInputs;
private static readonly string[] WsNames =
{
"NoTitleBar", "NoResize", "NoMove", "NoScrollbar", "NoScrollWithMouse", "NoCollapse", "AlwaysAutoResize",
"NoBackground", "NoSavedSettings", "NoMouseInputs", "MenuBar", "HorizontalScrollbar", "NoFocusOnAppearing",
"NoBringToFrontOnFocus", "AlwaysVerticalScrollbar", "AlwaysHorizontalScrollbar", "NoNavInputs", "NoNavFocus",
"UnsavedDocument", "NoDocking",
};
/// <summary>
/// hud.WindowSettings: the honoured ImGuiWindowFlags map onto the hud's fields (NoTitleBar =
/// chrome "none", NoInputs/NoMouseInputs = click-through, NoBackground, NoScrollbar,
/// NoScrollWithMouse). Everything else (AlwaysAutoResize until Phase 2 included) is ignored
/// with one console warning per hud.
/// </summary>
internal void SetHudWindowSettings(ScriptHud hud, long flags)
{
hud.WindowSettings = flags;
hud.ChromeNone = (flags & WsNoTitleBar) != 0;
hud.ClickThrough = (flags & WsNoMouseInputs) != 0;
hud.NoBackground = (flags & WsNoBackground) != 0;
hud.NoScrollbar = (flags & WsNoScrollbar) != 0;
hud.NoScrollWithMouse = (flags & WsNoScrollWithMouse) != 0;
hud.PropsDirty = true;
hud.PassNow = true;
long ignored = flags & ~(WsHonoured | WsQuiet);
if (ignored == 0 || hud.WindowSettingsWarned) return;
hud.WindowSettingsWarned = true;
var names = new List<string>();
for (int bit = 0; bit < 63; bit++)
if ((ignored & (1L << bit)) != 0) names.Add(bit < WsNames.Length ? WsNames[bit] : $"bit {bit}");
hud.Ctx.Host.Print($"hud {hud.Name}: WindowSettings {string.Join(", ", names)} ignored (script windows honour NoTitleBar, NoScrollbar, NoScrollWithMouse, NoBackground and NoInputs)");
}
internal void DisposeHud(ScriptHud hud)
{
if (hud.Disposed) return;
hud.Disposed = true;
hud.OnRender.Clear();
hud.OnPreRender.Clear();
hud.OnShow.Clear();
hud.OnHide.Clear();
_huds.Remove(hud);
_hudsByHash.Remove(hud.Hash);
_hudSetChanged = true;
}
private void RemoveHudsOf(ScriptContext ctx)
{
foreach (ScriptHud h in _huds.Where(h => h.Ctx == ctx).ToList())
DisposeHud(h);
}
// ── Tick ────────────────────────────────────────────────────────────────
/// <summary>Step 1: events from the engine to their huds.</summary>
private void PollHudEvents()
{
if (_huds.Count == 0 && !_hudsEverSubmitted) return;
RefreshUiInfo(force: false);
if (!Host.HasUi) return;
for (int round = 0; round < 8; round++)
{
int n = Host.UiPollEvents(_eventBuffer, out int remaining);
if (n > 0) ApplyHudEvents(_eventBuffer.AsSpan(0, n));
if (remaining == 0) break;
if (n == 0) Array.Resize(ref _eventBuffer, _eventBuffer.Length * 2); // one event didn't fit
}
}
private void ApplyHudEvents(ReadOnlySpan<byte> data)
{
int pos = 0;
while (data.Length - pos >= 16)
{
ushort type = BinaryPrimitives.ReadUInt16LittleEndian(data[pos..]);
int size = BinaryPrimitives.ReadUInt16LittleEndian(data[(pos + 2)..]);
if (size < 16 || size > data.Length - pos) break;
uint seq = BinaryPrimitives.ReadUInt32LittleEndian(data[(pos + 4)..]);
uint window = BinaryPrimitives.ReadUInt32LittleEndian(data[(pos + 8)..]);
uint key = BinaryPrimitives.ReadUInt32LittleEndian(data[(pos + 12)..]);
ReadOnlySpan<byte> p = data.Slice(pos + 16, size - 16);
pos += size;
if (seq > _lastPolledSeq) _lastPolledSeq = seq;
_hudsByHash.TryGetValue(window, out ScriptHud? hud);
switch (type)
{
case HudFormat.EvClicked when hud != null && p.Length >= 2:
hud.Clicks[key] = (hud.Clicks.TryGetValue(key, out int c) ? c : 0) + BinaryPrimitives.ReadUInt16LittleEndian(p);
hud.NoteUnapplied(seq);
break;
case HudFormat.EvBool when hud != null && p.Length >= 1:
hud.Bools[key] = p[0] != 0;
hud.NoteUnapplied(seq);
break;
case HudFormat.EvInt when hud != null && p.Length >= 4:
hud.Ints[key] = BinaryPrimitives.ReadInt32LittleEndian(p);
hud.NoteUnapplied(seq);
break;
case HudFormat.EvFloat when hud != null && p.Length >= 4:
{
float f = BinaryPrimitives.ReadSingleLittleEndian(p);
if (!float.IsFinite(f)) break;
hud.Floats[key] = f;
hud.NoteUnapplied(seq);
break;
}
case HudFormat.EvText when hud != null && p.Length >= 3:
{
bool submitted = p[0] != 0;
int n = Math.Min(BinaryPrimitives.ReadUInt16LittleEndian(p[1..]), p.Length - 3);
string text = Encoding.UTF8.GetString(p.Slice(3, n));
// "submitted" stays set until a pass takes it, as the engine's queue does.
if (hud.Texts.TryGetValue(key, out var old) && old.Submitted) submitted = true;
hud.Texts[key] = (text, submitted);
hud.NoteUnapplied(seq);
break;
}
case HudFormat.EvOpen when hud != null && p.Length >= 1:
hud.OpenStates[key] = p[0] != 0;
hud.NoteUnapplied(seq);
break;
case HudFormat.EvGeometry when hud != null && p.Length >= 36:
{
// Feeds GetWindowSize and friends; no pass, no AckSeq hold.
uint gf = BinaryPrimitives.ReadUInt32LittleEndian(p[32..]);
hud.Geometry = new HudGeometry
{
WindowPos = ReadVec2(p, 0),
WindowSize = ReadVec2(p, 8),
ContentAvail = ReadVec2(p, 16),
CursorStart = ReadVec2(p, 24),
Focused = (gf & HudFormat.GeoFocused) != 0,
Hovered = (gf & HudFormat.GeoHovered) != 0,
Known = true,
};
break;
}
case HudFormat.EvVisibility when hud != null && p.Length >= 1:
OnPlayerVisibility(hud, p[0] != 0, p.Length >= 2 ? p[1] : (byte)0);
break;
case HudFormat.EvError when p.Length >= 2:
{
int n = Math.Min(BinaryPrimitives.ReadUInt16LittleEndian(p), p.Length - 2);
string text = Encoding.UTF8.GetString(p.Slice(2, n));
if (hud != null) hud.Ctx.Host.Print($"hud {hud.Name}: {text}");
else Log("[RynthLua] script windows: " + text);
break;
}
}
}
}
private static System.Numerics.Vector2 ReadVec2(ReadOnlySpan<byte> p, int at)
{
float x = BinaryPrimitives.ReadSingleLittleEndian(p[at..]);
float y = BinaryPrimitives.ReadSingleLittleEndian(p[(at + 4)..]);
return new System.Numerics.Vector2(float.IsFinite(x) ? x : 0f, float.IsFinite(y) ? y : 0f);
}
/// <summary>Step 3: render passes for the huds that are due, within the pass slice.</summary>
private void RunHudPasses()
{
if (_huds.Count == 0) return;
RefreshUiInfo(force: false);
if (!_uiAvailable) return;
long now = Stopwatch.GetTimestamp();
long deadline = now + PassSliceTicks;
int n = _huds.Count;
int start = _hudRotation++ % n;
// §2.3: first the huds with a pass due now whatever their rate (input arrived, just
// shown, a property changed); then the ones whose RefreshRate interval has passed,
// round-robin. When the 1.5 ms slice runs out the rest wait for the next tick.
for (int pass = 0; pass < 2; pass++)
{
for (int k = 0; k < n; k++)
{
if (Stopwatch.GetTimestamp() >= deadline) return;
if (k >= _huds.Count) break;
ScriptHud hud = _huds[(start + k) % _huds.Count];
if (!PassDue(hud, pass == 0, now)) continue;
long interval = PassInterval(hud);
// Interval passes keep their cadence (a pump tick landing just after the due
// time doesn't push every later pass back); a pass out of turn starts a new one.
hud.NextPassAt = !hud.PassNow && now - hud.NextPassAt < interval ? hud.NextPassAt + interval : now + interval;
hud.PassNow = false;
RunPass(hud);
}
}
}
/// <summary>
/// Whether <paramref name="hud"/> runs a pass this tick. <paramref name="urgent"/>: only
/// passes due whatever the rate (PassNow); otherwise only interval passes. Hidden huds,
/// huds of scripts that aren't loaded and huds stopped after 20 errors run none.
/// </summary>
private static bool PassDue(ScriptHud hud, bool urgent, long now)
{
if (hud.Disposed || !hud.Visible || !hud.Ctx.Host.Loaded) return false;
if (hud.ErrorStreak >= HudErrorStrikes) return false;
return urgent ? hud.PassNow : now >= hud.NextPassAt;
}
/// <summary>Stopwatch ticks between interval passes: hud.RefreshRate (1..60) per second.</summary>
private static long PassInterval(ScriptHud hud) =>
Stopwatch.Frequency / Math.Clamp(hud.RefreshRate, MinRefreshRate, MaxRefreshRate);
private const string PassRunnerKey = "rynth.hudpass";
/// <summary>One render pass: OnPreRender + OnRender in one coroutine under the instruction cap.</summary>
private void RunPass(ScriptHud hud)
{
Script? s = hud.Ctx.Host.Lua;
if (s == null) return;
DynValue runner = s.Registry.Get(PassRunnerKey);
if (runner.Type != DataType.Function)
{
runner = s.LoadString("local list = ... for i = 1, #list do list[i]() end", null, "hud pass");
s.Registry.Set(PassRunnerKey, runner);
}
long t0 = Stopwatch.GetTimestamp();
int gc0 = GC.CollectionCount(0), gc1 = GC.CollectionCount(1), gc2 = GC.CollectionCount(2);
// SetNextWindowSize/Pos are per-pass requests: OnPreRender sets them again every pass.
// A failed pass keeps the last good pass's requests (as it keeps its list).
var savedRequestSize = hud.RequestSize;
var savedRequestPos = hud.RequestPos;
bool savedPosIsDefault = hud.PosIsDefault;
hud.RequestSize = HudFormat.NoRequest;
hud.RequestPos = HudFormat.NoRequest;
hud.PosIsDefault = false;
var list = new Table(s);
foreach (DynValue fn in hud.OnPreRender.TakeForCall()) list.Append(fn);
foreach (DynValue fn in hud.OnRender.TakeForCall()) list.Append(fn);
_recorder.Begin(hud, _maxOps, _maxBytes);
string? error = null;
try
{
DynValue co = s.CreateCoroutine(runner);
co.Coroutine.AutoYieldCounter = PassInstructionCap;
DynValue r = co.Coroutine.Resume(DynValue.NewTable(list));
if (co.Coroutine.State != CoroutineState.Dead)
{
error = r.Type == DataType.YieldRequest
? $"OnRender ran too long (over {PassInstructionCap} instructions); the last good frame stays"
: "sleep/await can't be used in OnRender; use spawn";
if (r.Type == DataType.YieldRequest) _statAborts++;
}
}
catch (InterpreterException ex) { error = ex.DecoratedMessage ?? ex.Message; }
catch (Exception ex) { error = ex.Message; }
if (error != null)
{
// An error can quote a huge string (error(string.rep(...))): keep what the window,
// the console and hud.LastError can use, not megabytes per failed pass.
if (error.Length > MaxHudErrorChars) error = error[..MaxHudErrorChars] + "...";
_recorder.Abort();
hud.ConsumedInput = false;
hud.RequestSize = savedRequestSize;
hud.RequestPos = savedRequestPos;
hud.PosIsDefault = savedPosIsDefault;
if (hud.LastError != error) hud.PropsDirty = true; // the window shows the error above the last good list
hud.LastError = error;
hud.ErrorStreak++;
long nowMs = Environment.TickCount64;
if (nowMs - hud.LastErrorPrintAt >= 5000)
{
hud.LastErrorPrintAt = nowMs;
hud.Ctx.Host.Print($"hud {hud.Name}: {error}");
}
if (hud.ErrorStreak == HudErrorStrikes)
{
hud.Ctx.Host.Print($"hud {hud.Name} stopped drawing after {HudErrorStrikes} errors in a row; hide and show it (or restart the script) to try again");
hud.DropPendingInput(); // no pass will take it; don't hold the AckSeq for it
}
}
else
{
_recorder.End();
hud.ErrorStreak = 0;
if (hud.LastError != null) hud.PropsDirty = true;
hud.LastError = null;
hud.FirstPassSinceShown = false;
hud.EverPassed = true;
// Results the pass didn't draw a widget for are stale (the widget is gone).
foreach (uint key in hud.Clicks.Keys.ToList())
if (!hud.SeenKeys.Contains(key) || hud.Clicks[key] <= 0) hud.Clicks.Remove(key);
hud.Bools.Clear();
hud.Ints.Clear();
hud.Floats.Clear();
hud.Texts.Clear();
PruneOpenStates(hud);
if (hud.Clicks.Count == 0) hud.FirstUnappliedSeq = 0;
else hud.PassNow = true; // another click is waiting: one per pass
// Submit on change; a pass that consumed input is always sent, so the engine
// sees its AckSeq move even when the picture didn't change.
ReadOnlySpan<byte> recorded = hud.Scratch.AsSpan(0, hud.ScratchLength);
if (hud.ConsumedInput || !recorded.SequenceEqual(hud.Body.AsSpan(0, hud.BodyLength)))
{
(hud.Body, hud.Scratch) = (hud.Scratch, hud.Body);
hud.BodyLength = hud.ScratchLength;
hud.ListSeq++;
hud.BodyDirty = true;
}
hud.ConsumedInput = false;
_statMaxOps = Math.Max(_statMaxOps, hud.OpCount);
_statOps += hud.OpCount;
}
long ticks = Stopwatch.GetTimestamp() - t0;
// Phase 0 diagnostics: what a slow pass (over 10 ms) was spent on.
if (ticks > Stopwatch.Frequency / 100 && Environment.TickCount64 - _lastSlowLogAt > 2000)
{
_lastSlowLogAt = Environment.TickCount64;
Log($"[RynthLua] slow hud pass: {ticks * 1000.0 / Stopwatch.Frequency:F1} ms, hud {hud.Name}, ops {hud.OpCount}, " +
$"GCs during it gen0 {GC.CollectionCount(0) - gc0} gen1 {GC.CollectionCount(1) - gc1} gen2 {GC.CollectionCount(2) - gc2}, " +
$"heap {GC.GetTotalMemory(false) / (1024 * 1024)} MB");
}
_statPasses++;
_statPassTicks += ticks;
_statPassMax = Math.Max(_statPassMax, ticks);
}
/// <summary>A widget's pending click (one per pass while the count is above zero).</summary>
internal bool TakeClick(ScriptHud hud, uint key)
{
if (!hud.Clicks.TryGetValue(key, out int count) || count <= 0) return false;
hud.Clicks[key] = count - 1;
hud.ConsumedInput = true;
return true;
}
/// <summary>A widget's pending new bool value, if the player changed it.</summary>
internal bool TakeBool(ScriptHud hud, uint key, out bool value)
{
if (!hud.Bools.Remove(key, out value)) return false;
hud.ConsumedInput = true;
return true;
}
/// <summary>A SliderInt's or Combo's pending new value (Combo: the 0-based index).</summary>
internal bool TakeInt(ScriptHud hud, uint key, out int value)
{
if (!hud.Ints.Remove(key, out value)) return false;
hud.ConsumedInput = true;
return true;
}
/// <summary>A SliderFloat's pending new value.</summary>
internal bool TakeFloat(ScriptHud hud, uint key, out float value)
{
if (!hud.Floats.Remove(key, out value)) return false;
hud.ConsumedInput = true;
return true;
}
/// <summary>An InputText's pending new text; <paramref name="submitted"/>: Enter was pressed (EnterReturnsTrue).</summary>
internal bool TakeText(ScriptHud hud, uint key, out string text, out bool submitted)
{
if (!hud.Texts.Remove(key, out var t))
{
text = string.Empty;
submitted = false;
return false;
}
text = t.Text;
submitted = t.Submitted;
hud.ConsumedInput = true;
return true;
}
/// <summary>A CollapsingHeader's or TreeNode's open state: what the player last set, else the default.</summary>
internal static bool GetOpenState(ScriptHud hud, uint key, bool defaultOpen) =>
hud.OpenStates.TryGetValue(key, out bool open) ? open : defaultOpen;
private readonly List<uint> _pruneKeys = new();
/// <summary>Drops the open states of headers and trees the pass didn't draw.</summary>
private void PruneOpenStates(ScriptHud hud)
{
if (hud.OpenStates.Count == 0) return;
_pruneKeys.Clear();
foreach (uint key in hud.OpenStates.Keys)
if (!hud.SeenKeys.Contains(key)) _pruneKeys.Add(key);
foreach (uint key in _pruneKeys) hud.OpenStates.Remove(key);
}
/// <summary>Step 4: the complete window set, bodies only for the huds whose list changed.</summary>
private void SubmitHuds(bool force = false)
{
if (!Host.HasUi) return;
bool changed = _hudSetChanged || force;
foreach (ScriptHud h in _huds)
{
// Any header field that differs from what the engine last accepted (properties,
// per-pass requests, the error line) needs a submit.
if (!h.PropsDirty && (!h.HeaderSubmitted || !h.Header().SameAs(h.SubmittedHeader))) h.PropsDirty = true;
if (h.BodyDirty || h.PropsDirty) changed = true;
}
if (!changed) return;
if (_huds.Count == 0 && !_hudsEverSubmitted) { _hudSetChanged = false; return; }
long now = Stopwatch.GetTimestamp();
if (!force && now < _submitRetryAt) return;
// AckSeq: every event up to here has been applied, except in huds still waiting for a
// pass. A hud that can't run one (hidden, stopped, script not loaded) holds nothing back:
// the engine ignores every window's Visible flag while the AckSeq is below its last
// player visibility change, so a stuck hold would freeze them all.
uint ack = _lastPolledSeq;
foreach (ScriptHud h in _huds)
if (h.FirstUnappliedSeq != 0 && h.Visible && h.ErrorStreak < HudErrorStrikes && h.Ctx.Host.Loaded)
ack = Math.Min(ack, h.FirstUnappliedSeq - 1);
// Bodies that don't fit in the engine's per-submit limit wait for a later tick (still
// dirty); the start rotates so a busy hud can't keep the others waiting.
int count = Math.Min(_huds.Count, HudsPerPlugin);
int pos = HudFormat.WriteSubmit(ref _submitBuffer, _huds, count, ack, _maxSubmitBytes, _submitRotation++);
long t0 = Stopwatch.GetTimestamp();
int rc = Host.UiSubmit(_submitBuffer.AsSpan(0, pos));
_statSubmitTicks += Stopwatch.GetTimestamp() - t0;
if (rc == 0)
{
foreach (ScriptHud h in _huds)
{
if (h.BodyInSubmit) h.BodyDirty = false;
h.PropsDirty = false;
h.SubmittedHeader = h.Header();
h.HeaderSubmitted = true;
}
_hudSetChanged = false;
_hudsEverSubmitted = _huds.Count > 0;
_statSubmits++;
_statSubmitBytes += pos;
}
else
{
// Nothing was applied; the engine keeps the previous lists. Try again in a second.
_submitRetryAt = now + Stopwatch.Frequency;
if (Environment.TickCount64 - _lastSubmitErrorLog > 10_000)
{
_lastSubmitErrorLog = Environment.TickCount64;
Log($"[RynthLua] script windows: the engine refused the window list ({rc}); see the scripts' consoles");
}
}
}
/// <summary>Steps 3 and 4 plus the measurement log; after the scripts ran.</summary>
private void TickHuds()
{
RunHudPasses();
SubmitHuds();
LogHudStats();
}
/// <summary>Shutdown: the windows close with RynthLua (the engine drops them too).</summary>
private void ShutdownHuds()
{
foreach (ScriptHud h in _huds.ToList()) DisposeHud(h);
try { SubmitHuds(force: true); } catch { }
}
private void LogHudStats()
{
long now = Stopwatch.GetTimestamp();
if (_statsStart == 0) _statsStart = now;
if (now - _statsStart < StatsEveryTicks) return;
double seconds = (now - _statsStart) / (double)Stopwatch.Frequency;
_statsStart = now;
if (_statPasses > 0 || _statSubmits > 0)
{
double us(long t) => t * 1_000_000.0 / Stopwatch.Frequency;
int good = Math.Max(1, _statPasses - _statAborts);
string line = string.Create(CultureInfo.InvariantCulture,
$"[RynthLua] hud passes: {seconds:0.0}s passes={_statPasses} huds={_huds.Count(h => h.Visible)} "
+ $"us/pass avg={us(_statPassTicks) / Math.Max(1, _statPasses):0} max={us(_statPassMax):0} "
+ $"ops/pass avg={_statOps / (double)good:0} max={_statMaxOps} us/op={(_statOps > 0 ? us(_statPassTicks) / _statOps : 0):0.00} "
+ $"aborted={_statAborts} | submits={_statSubmits} bytes/submit={(_statSubmits > 0 ? _statSubmitBytes / _statSubmits : 0)} "
+ $"us/submit={(_statSubmits > 0 ? us(_statSubmitTicks) / _statSubmits : 0):0}");
Log(line);
}
_statPasses = _statAborts = _statSubmits = _statMaxOps = 0;
_statPassTicks = _statPassMax = _statOps = _statSubmitBytes = _statSubmitTicks = 0;
}
// ── /lua hud ────────────────────────────────────────────────────────────
private const string BenchScript = "hud-bench";
private void HandleHudCommand(string rest)
{
string[] p = rest.Split(' ', 2, StringSplitOptions.RemoveEmptyEntries);
string sub = p.Length > 0 ? p[0].ToLowerInvariant() : "";
switch (sub)
{
case "bench":
{
string arg = p.Length > 1 ? p[1].Trim() : "";
if (arg.Equals("off", StringComparison.OrdinalIgnoreCase) || arg.Equals("stop", StringComparison.OrdinalIgnoreCase))
{
ChatLine(StopScript(BenchScript) ? "Bench stopped." : "The bench isn't running.");
break;
}
if (!int.TryParse(arg, NumberStyles.Integer, CultureInfo.InvariantCulture, out int n) || n < 1)
{
ChatLine("Usage: /lua hud bench <widgets 1-1500> | /lua hud bench off");
break;
}
n = Math.Min(n, 1500);
if (!UiAvailable) { ChatLine("Script windows need RynthCore API v71 with ImGui on."); break; }
RunCode(BenchScript, BenchCode(n));
ChatLine($"Bench: a hud with {n} widgets. Measurements go to the log every ~10 s ('hud passes:' and 'ScriptWindows replay:'). /lua hud bench off to stop.");
break;
}
case "list":
ChatLine(HudListLine());
break;
case "show":
case "hide":
case "toggle":
{
string name = p.Length > 1 ? p[1].Trim() : "";
ScriptHud? hud = FindHud(name, out string? problem);
if (hud == null)
{
ChatLine((problem ?? $"No hud named '{name}'.") + " " + HudListLine());
break;
}
bool show = sub == "show" || sub == "toggle" && !hud.Visible;
bool changed = hud.Visible != show;
PlayerSetHudVisible(hud, show);
ChatLine($"{hud.Ctx.Name}/{hud.Name} {(show ? "shown" : "hidden")}{(changed ? "" : " (it already was)")}.");
break;
}
default:
ChatLine("/lua hud list | show|hide|toggle <script>/<hud> | bench <widgets 1-1500> | bench off");
break;
}
}
private string HudListLine()
{
if (_huds.Count == 0) return "No huds.";
return $"Huds ({_huds.Count}): " + string.Join(", ", _huds.Select(h =>
$"{h.Ctx.Name}/{h.Name}{(h.Visible ? " [shown]" : "")}{(h.LastError != null ? " [error]" : "")}{(h.ShowInBar ? "" : " [not in bar]")}"));
}
/// <summary>
/// A hud by "script/hud" (case-insensitive), or by the hud's name alone when only one hud
/// has it. Null with <paramref name="problem"/> set when the name is missing or ambiguous.
/// </summary>
internal ScriptHud? FindHud(string name, out string? problem)
{
problem = null;
name = (name ?? string.Empty).Trim();
if (name.Length == 0) { problem = "Which hud? Use <script>/<hud>."; return null; }
foreach (ScriptHud h in _huds)
if (!h.Disposed && string.Equals($"{h.Ctx.Name}/{h.Name}", name, StringComparison.OrdinalIgnoreCase)) return h;
ScriptHud[] byName = _huds.Where(h => !h.Disposed && string.Equals(h.Name, name, StringComparison.OrdinalIgnoreCase)).ToArray();
if (byName.Length == 1) return byName[0];
if (byName.Length > 1) problem = $"More than one hud is called '{name}'; use <script>/<hud>.";
return null;
}
/// <summary>N widgets: a counter line, then Text / Button / Checkbox in turn.</summary>
private static string BenchCode(int n) => $$"""
local views = require("views")
local ImGui = require("imgui")
local N = {{n}}
local hud = views.Huds.CreateHud("Bench")
hud.Title = "Bench (" .. N .. " widgets)"
hud.Visible = true
local checks, clicks = {}, 0
hud.OnRender.Add(function()
ImGui.Text("clicks: " .. clicks .. " widgets: " .. N)
for i = 2, N do
local m = i % 3
if m == 0 then
ImGui.Text("Text line " .. i)
elseif m == 1 then
if ImGui.Button("Button " .. i) then clicks = clicks + 1 end
else
local _, v = ImGui.Checkbox("Check " .. i, checks[i] or false)
checks[i] = v
end
end
end)
print("bench hud with " .. N .. " widgets; /lua hud bench off to stop")
""";
}

View file

@ -0,0 +1,56 @@
# RynthLua editor types
Completion, hover docs and type checks for RynthLua scripts in VS Code (or any editor
that uses the Lua language server, LuaLS / "sumneko").
| File | What it describes |
| --- | --- |
| `rynthlua.d.lua` | Everything: the globals (`game`, `sleep`, `await`, v1 `chat`/`me`/...), WorldObject, Character, World, Actions, ActionQueue, events and their argument tables, the module types, the enum tables, and script windows (`Vector2`, `Vector4`, the hud, the `imgui` functions and the ImGui enums) |
| `json.lua`, `storage.lua`, `enums.lua`, `filesystem.lua`, `rynthlua.lua`, `rynth/ai.lua` | Small stubs so `require("json")`, `require("rynth.ai")`, ... resolve to the right types |
| `views.lua`, `imgui.lua` | Stubs for `require("views")` and `require("imgui")` (script windows) |
None of these files are loaded in the game; they only describe the API. The reference is
`docs/RYNTHLUA.md` in RynthSuite.
## Setup (VS Code)
1. Install the **Lua** extension (publisher: sumneko).
2. Copy this `Types` folder somewhere stable, for example
`C:\Games\RynthSuite\RynthLua\Types`.
3. Open your scripts folder (`C:\Games\RynthSuite\RynthLua\Scripts`) in VS Code and put a
`.luarc.json` in it:
```json
{
"$schema": "https://raw.githubusercontent.com/LuaLS/vscode-lua/master/setting/schema.json",
"runtime.version": "Lua 5.2",
"workspace.library": ["C:/Games/RynthSuite/RynthLua/Types"],
"workspace.checkThirdParty": false,
"diagnostics.disable": ["lowercase-global"]
}
```
Use the path where you put the folder (forward slashes are fine). Reload the window
(`Developer: Reload Window`) after changing `.luarc.json`.
The same settings work in VS Code's `settings.json` with a `Lua.` prefix
(`"Lua.workspace.library": [...]`, `"Lua.runtime.version": "Lua 5.2"`).
## Notes
- RynthLua runs Lua 5.2 (MoonSharp), hence `runtime.version`.
- API tables are declared with dot calls (`game.World.GetAll()`,
`game.Actions.ObjectUse(id)`, `storage.Get("key")`), WorldObject methods with colon
calls (`wo:Use()`, `wo:DistanceTo(other)`). In the game both forms work everywhere, so if
the editor warns about `wo.Use()` or `game.World:GetAll()`, the script is still fine.
- Events: `game.World.OnTell.Add(function(e) ... end)`; the handler's `e` is typed, so
`e.` completes the event's fields.
- Script windows: `local hud = views.Huds.CreateHud("X")` is a `RynthLua.Hud`; inside
`hud.OnRender.Add(function() ... end)` the `ImGui.` calls complete with their arguments and
their extra return values (`local changed, v = ImGui.Checkbox("On", v)`).
- Enum-valued fields (`wo.ObjectClass`, `game.Character.CombatMode`, `e.Type`, ...) are
numbers typed as the enum, so `wo.ObjectClass == ObjectClass.Monster` checks cleanly.
- If a `require` doesn't pick up its type (an unusual `runtime.path`), annotate it by hand:
`local json = require("json") ---@type RynthLua.JsonModule`.
- A script's own modules (`require("helpers")` for `helpers.lua` next to `index.lua`)
resolve normally when the script's folder is the open workspace.

View file

@ -0,0 +1,64 @@
---@meta enums
-- Editor definitions for require("enums") (RynthLua). Not loaded in the game.
-- The same tables are globals in every script.
return {
ObjectClass = ObjectClass,
SkillId = SkillId,
AttributeId = AttributeId,
VitalId = VitalId,
CombatMode = CombatMode,
IntId = IntId,
BoolId = BoolId,
StringId = StringId,
ChatType = ChatType,
AmmoType = AmmoType,
AttackHeight = AttackHeight,
CharacterOptions1 = CharacterOptions1,
CharacterOptions2 = CharacterOptions2,
ContainerProperties = ContainerProperties,
CoverageMask = CoverageMask,
CreatureType = CreatureType,
DamageType = DamageType,
DataId = DataId,
EnchantmentFlags = EnchantmentFlags,
EndTradeReason = EndTradeReason,
EquipMask = EquipMask,
FloatId = FloatId,
Gender = Gender,
HeritageGroup = HeritageGroup,
IconHighlight = IconHighlight,
InstanceId = InstanceId,
Int64Id = Int64Id,
MagicSchool = MagicSchool,
MaterialType = MaterialType,
MotionStance = MotionStance,
ObjectDescriptionFlag = ObjectDescriptionFlag,
ObjectType = ObjectType,
PhysicsState = PhysicsState,
PlayScript = PlayScript,
RadarBehavior = RadarBehavior,
RadarColor = RadarColor,
SkillTrainingType = SkillTrainingType,
SpellCategory = SpellCategory,
SpellFlags = SpellFlags,
SpellType = SpellType,
TradeSide = TradeSide,
UsableType = UsableType,
Vital = Vital,
WeenieError = WeenieError,
WeenieType = WeenieType,
WieldType = WieldType,
AddRemoveEventType = AddRemoveEventType,
BusyAction = BusyAction,
CastEventType = CastEventType,
ChatChannel = ChatChannel,
ClientCapability = ClientCapability,
ClientConfirmationType = ClientConfirmationType,
DistanceType = DistanceType,
FellowshipEventType = FellowshipEventType,
ScriptStartupType = ScriptStartupType,
UseActionType = UseActionType,
ChatMessageType = ChatMessageType,
ClientState = ClientState,
}

View file

@ -0,0 +1,6 @@
---@meta filesystem
-- Editor definitions for require("filesystem") (RynthLua). Not loaded in the game.
---@type RynthLua.FileSystemModule
local filesystem
return filesystem

View file

@ -0,0 +1,6 @@
---@meta imgui
-- Editor definitions for require("imgui") (RynthLua script windows). Not loaded in the game.
---@type RynthLua.ImGui
local ImGui
return ImGui

View file

@ -0,0 +1,6 @@
---@meta json
-- Editor definitions for require("json") (RynthLua). Not loaded in the game.
---@type RynthLua.JsonModule
local json
return json

View file

@ -0,0 +1,6 @@
---@meta rynth.ai
-- Editor definitions for require("rynth.ai") (RynthLua). Not loaded in the game.
---@type RynthLua.RynthAiModule
local ai
return ai

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,6 @@
---@meta rynthlua
-- Editor definitions for require("rynthlua") (RynthLua). Not loaded in the game.
---@type RynthLua.InfoModule
local rynthlua
return rynthlua

View file

@ -0,0 +1,6 @@
---@meta storage
-- Editor definitions for require("storage") (RynthLua). Not loaded in the game.
---@type RynthLua.StorageModule
local storage
return storage

View file

@ -0,0 +1,6 @@
---@meta views
-- Editor definitions for require("views") (RynthLua script windows). Not loaded in the game.
---@type RynthLua.ViewsModule
local views
return views