Snapshot for release 2026.10.13.1 (internal d2b5fb3)

This commit is contained in:
Tom Bohar 2026-10-13 14:25:49 -04:00
commit 319740ff5d
291 changed files with 58505 additions and 2107 deletions

View file

@ -0,0 +1,64 @@
# RynthAi: Mini Remote right-click menu with Character and server sections; Spells added
Pairs with the matching RynthCore commit on `sk`, which sends the server sections.
## What changed
- **Right-clicking the Mini Remote** (its Remote tab, in the floating window, RynthCore's Mini
Remote window or the dashboard drawer) now opens a menu in two halves:
- **Character** (top): windows every server has.
- **Spells**: the spell catalog and buff profile editor, the same window as `/ra spells`.
- **Skills**, **Inventory** and **Item Count**: RynthCore panels. They are listed when
RynthCore can run `/rc` commands.
- **Inventory HUDs setup**.
- **Server section** (bottom): the windows of the server plugins installed for the world
you're on.
- RynthCore decides the list: which server you're on, which plugins are installed and what
each one adds. It sends the list to RynthAi (the `"servermenu"` remote command, parsed by
`Huds/ServerMenuModel.cs`).
- On Infinite Leaftide it lists:
- the Mini Remote's Character, Quests, Pets, Banking, Gear and Games tabs (each greyed out
until the server reports that feature on);
- Guardian (RynthAi);
- Bounties (RynthILT, only when installed);
- Progression.
- A server's section shows only while you're on that server or it is forced, and only when
one of its plugins is installed. A new server or server plugin only needs registering in
RynthCore; this menu doesn't change.
- Forcing: when no installed server plugin matches the world, the section offers
"Treat this world as <server>".
- For Infinite Leaftide this turns on RynthCore's session override (`/rc ilt on`) and this
character's "Treat this world as ILT".
- With that per-character override on, the Infinite Leaftide section shows even when
RynthCore doesn't detect ILT. It is labelled "(forced)".
- With an older RynthCore, or its ImGui layer off, no list arrives. The menu then falls back
to RynthAi's own Infinite Leaftide entries.
- The server-features status line, the "Treat this world as ILT" checkbox and "Refresh server
features" moved from the Options menu to the Infinite Leaftide section.
- **The Options button** now holds only the Mini Remote's settings: sections, layout, slot size,
lock and hide, and Inventory HUDs setup.
- **Fix:** the Options button didn't open its menu while the tab bar was showing. The button sits
inside the Remote tab, whose ID ImGui adds to the popup's. The popup now opens at window level.
## Files
- `Huds/ServerMenuModel.cs`: new. It parses the `"servermenu"` payload and recognizes
`tab:<id>` items.
- `Huds/MiniRemoteHud.cs`:
- the right-click menu (`RenderMenu`, `RenderCharacterMenu`, `RenderServerMenu`,
`RenderLocalIltMenu`, `RenderIltStatus`);
- the Options popup is now opened from a flag (`_openOptions`).
- `Huds/HudController.cs`: `RunEngineCommand`, which runs a `/rc` command on the pump thread.
- `RynthAiPlugin.cs`: the `servermenu` remote command, handled before settings exist.
- `Tools/RynthCore.RynthAiHostTests/Tests/ServerMenuTests.cs`: new (payload parsing, malformed
lines, tab features).
## Testing
- Host tests: 616 of 617 pass. The one failure is the known map-bake test, which needs the real
dat files. The three new server menu tests pass.
- In game: right-click the Mini Remote on and off an ILT world. Check that:
- the Character half shows Spells, Skills, Inventory and Item Count;
- the Infinite Leaftide half appears only on ILT, or when forced;
- the tab items switch tabs;
- Guardian and Bounties open their panels.

View file

@ -0,0 +1,81 @@
# Mini Remote: a Charms tab, and Banking brought up to date with ACECustom's /bank
Pairs with the matching RynthCore commit on `sk`.
## Charms tab (ILT)
- **New Mini Remote tab, Charms.** It sits after Gear and replaces both the engine's Settings >
Charms Tracking page and the charm toggles that were on the Gear tab.
- **Summary line:** how many charms are acquired and how many are active, with a Refresh button.
- **The table has one row per ACECustom registry charm**, with these columns:
- Charm (hover for its effect);
- Acquired: Carried, Stored (carried before, remembered per character) or No;
- Status: ON, OFF, or ? while its appraisal is pending;
- Tier;
- Server: Enabled, Disabled, or - when not reported;
- a Toggle button that uses the carried copy. When several copies are carried, it uses the one
that's ON.
- **Guardian Hand** rows follow, each with its own Toggle, plus a "Guardian Hand matching" note.
- The tab rescans every 3 s while the Mini Remote window is open. Toggles are refused while an
item action is already waiting.
- **Gear tab:** the charm strip is gone. Dispel / Surging Strength now opens by default, and a note
says where the charms went.
- **Where to open it:**
- the Mini Remote tab bar;
- the local ILT menu;
- `/ra hub open charms` (`charm` also works);
- the engine's ILT server menu (the matching engine).
- `GetCharmsJson` stays exported for older engines, which still have the Settings page.
## Banking (ILT), per ACECustom upstream `/bank` (2026-10-11)
- **Prestige Coins** balance row, read from `/bank`. The Mini Remote's bank strip shows "PC:" when
you have some, and the copy line includes them.
- **Deposit:** pick what to deposit and press Deposit. The choices are Everything, Pyreals,
Pyreal peas, Luminance, Luminance tokens (`/b lum`), Legendary keys, Mythical keys,
Enlightened coins, Weakly enlightened coins, Prestige coins and Trade notes.
- **Withdraw:** pick a kind and type an amount. The kinds are Pyreals, Luminance, Legendary keys,
Mythical keys, Enlightened coins, Weakly enlightened coins, Prestige coins and Trade notes.
- Trade notes take a denomination (100 to 250,000) and a count of up to 50,000. The panel shows
the total in pyreals.
- Bad input is refused before anything is sent.
- The server's reply lines (Deposited, Withdrew, refusals) show under the buttons. The balances
refresh 1.5 s after each action.
- **Throttles:**
- Deposits, withdrawals and transfers share the server's 5 s bank-action spacing.
- Plain balance refreshes are spaced on their own, so they no longer hold up an action.
- **Session rates:** money moved between the bank and your pack is no longer counted as income.
While a deposit, withdrawal or transfer is under way (about 12 s, extended by each Deposited or
Withdrew line), bank and pack changes are not added to the income figures.
## Files
- `IltHub/IltCharms.cs` (new): the Charms tab.
- `IltHub/IltCharmTracker.cs`: `CharmState.ToggleId`, the copy to use.
- `IltHub/IltGear.cs`: charm strip removed.
- `IltHub/IltSections.cs`, `IltHubController.cs`, `IltHubUi.cs`, `HudState.cs`: the tab is wired in.
- `IltHub/IltBankCommands.cs` (new): deposit and withdraw command building, and reply recognition.
It has no dependencies, so it can be tested on its own.
- `IltHub/IltBanking.cs`, `IltHubState.cs`: Prestige Coins, the deposit and withdraw UI, and the
throttles.
- `IltHub/IltSessionRates.cs`: ignores money moves.
- `Huds/MiniRemoteHud.cs`: the "PC:" cell.
## Tests
- `Tests/BankCommandTests.cs`, 4 new tests:
- deposit commands;
- withdraw commands, including trade notes;
- withdraw input refusals;
- reply-line recognition.
- `Tests/InventoryAttributeFilterTests.cs`, 5 new tests of the engine's inventory filter (the
engine file is linked into the test project):
- each rule kind;
- items not yet identified;
- match all vs match any;
- value conversions and names;
- the saved settings line.
Result: 636 of 637 pass. The one failure is the known map-bake test, which needs local dats.
Not yet tested in game.

View file

@ -0,0 +1,40 @@
# RynthAi: corpses with several keeps are looted to the end
## What Silentkelpie saw (2026-10-11, flight recorder 23:13)
Corpses with three or four keeps (Necrolytic Extracts, Coalesced Aetheria) were closed with
items still on them. On corpse 0xF021B0AB:
- 22:59:47.07 first pickup sent; the server merges it into the pack's stack (StackableMerge),
InventoryRemoveObject at 48.88.
- 22:59:53.01 second pickup sent, 4.1 s later, with nothing happening in between. InventoryRemoveObject at 54.83.
- 22:59:58.60 corpse closed: the 12 s LootCorpseTimeoutMs ran out. Everything else on it was left.
## Causes
1. **A merged item was never "in the inventory".** The pickup counts as done once the item shows
up in a pack. A stack merge removes the picked object, and the client keeps no container for it,
so it never showed up there. Each stackable keep waited the full PickupArriveMaxMs (4 s)
before the next pickup went out.
2. **The corpse timeout counted from the claim, not from the last progress.** With about 6 s per
stackable item, three of them used up the 12 s, and the corpse was abandoned mid-loot.
## Fix (CorpseOpenController)
- An item that left the corpse and has no container is taken as merged into a stack. It is
confirmed once its bend-down has played, about 1 s, with the reason "merged into a stack in the pack".
- Every confirmed pickup restarts the corpse timeout. The timeout now means 12 s without taking anything.
## Tests (LootCorpseTests)
- `loot pacing: an item merged into a stack in the pack is confirmed without the 4 s arrival wait`
(before: 4064 ms).
- `loot pacing: each item taken restarts the corpse timeout, so a corpse with many keeps is looted to the end`
(before: 1 of 3 taken, then abandoned).
## Not fixed here
On corpse 0xF0266213 (23:12:47 to 23:13:00) the client sent its own Use on the open corpse about
2 s after each merge. RynthAi did not send it (it has no engine marker in the recorder). That Use
closed the corpse, and RynthAi reopened it each time, at about 5 s per item. Something
other than RynthAi's loot path sent it: another plugin, or a click or key.

View file

@ -0,0 +1,47 @@
# Items: Remove Missing (clean out items no longer in your inventory)
Pairs with the matching RynthCore commit on `sk`, which adds the Remove Missing button to the Items panel.
## Why
The Items lists (weapons and consumables) keep an entry for every item ever added. Sold, dropped,
traded or used-up items stayed listed. The lists were cleaned only once: when a profile copied
from another character was first loaded.
## What changed
- **Remove Missing:** a new button at the top of the engine's Items panel, and a new chat command,
`/ra items clean`. Both drop listed weapons and consumables whose item is no longer in your
inventory. Your inventory means the main pack, side packs and wielded gear.
- **Re-pointing instead of removing:** when an entry's item is gone but your pack holds an
unlisted item with the same name (a new stack of healing kits, a replacement weapon), the entry
is pointed at that item. Its element or type stays as you set it.
- **Duplicates:** a second entry for an item that is already listed is removed.
- **Safe while loading:** nothing is removed while your inventory is still arriving after login,
or while the inventory reads as empty.
- **Report:** a chat line lists what was removed and what was re-pointed.
- **Profile copy check:** the one-time check on a profile copied from another character uses the
same rules. Before, it kept a dead entry whenever any item of that name existed; now it
re-points the entry or removes the duplicate.
- `/ra items` with no argument now lists both `fill` and `clean`.
## Files
- `LegacyUi/LegacyWeaponsUi.cs`: `CleanMissing` (`PruneNotOwned` now calls it).
- `LegacyUi/LegacyDashboardRenderer.cs`: `CleanMissingItems`, with the loading guards and the
chat report.
- `RynthAiCommands.cs`, `RynthAiPlugin.cs`: `/ra items clean`.
- `PluginExports.cs`: the `RynthPluginCleanItems` export, used by the engine button.
## Tests
`Tools/RynthCore.RynthAiHostTests/Tests/ItemsCleanTests.cs`, 3 new tests:
- gone entries are removed and owned ones are kept;
- a gone entry is re-pointed at an unlisted item of the same name (case-insensitive), keeping its
element;
- a gone duplicate of an item that is already listed is removed, not re-pointed.
Result: 622 of 623 pass. The one failure is the known map-bake test, which needs local dats.
Not yet tested in game.

View file

@ -0,0 +1,31 @@
# RynthAi: corpse items the object cache missed are looted
## The bug
Silentkelpie, 2026-10-11: a Necrolytic Extract on his own kill was left on the corpse. The
loot profile had Keep rules for it (by name), and there was no `[LootEval]` line for it at all.
Corpse looting only judges what `WorldObjectCache.GetContainedItems` returns, and that only
holds objects the cache has classified. The cache never processed a create for the extract,
so it was in neither the inventory nor the landscape set. The looter never saw it, judged the
other 13 items, and finished the corpse. When the corpse went away the cache logged the extract
as `DELETE-BEFORE-CLASSIFY`. The loot rules themselves were fine: the same profile keeps a
"Necrolytic Extract" (class Misc) with rule 57.
## The fix
While a corpse is open, every 500 ms the looter asks the client what the corpse holds
(`GetContainerContents`). It looks up any item the cache is missing (the cache's lazy lookup
files it) and judges it like the rest. A rescue is logged at Trace:
[RynthAi] Corpse loot: found 1 item(s) on 0xF0703900 the object cache had missed: 0xF0703199 'Necrolytic Extract' Misc.
An engine without `GetContainerContents` behaves as before.
## Tests
`LootCorpseTests`:
- an item whose create never reached the cache is found and looted;
- with no `GetContainerContents`, nothing changes and nothing breaks.
`FakeHost.ContentsCalls` is a new opt-in fake for `GetContainerContents`.

View file

@ -0,0 +1,82 @@
# RynthAi: the ILT Hub becomes the Mini Remote's tabs
Pairs with the matching RynthCore commit on `sk`, which adds the Guardian panel under the bar's ILT button.
## What changed
The ILT Hub and the Mini Remote are now one window, called **Mini Remote**.
- **Tabs.** The Mini Remote has a tab bar: **Remote** (the existing sections), then on ILT
worlds **Character, Quests, Pets, Banking, Gear and Games**.
- Each tab shows once the server reports that ILT feature on.
- Off ILT worlds there is no tab bar, so the Mini Remote looks as it did before.
- The selected tab is saved per character in `huds.json` (`MiniRemoteTab`).
- Each ILT tab draws at a fixed size, and the window follows it. Both the floating window and
RynthCore's Mini Remote window refit when the tab changes.
- Right-click Options belongs to the Remote tab. The ILT tabs keep their own right-click menus.
- The dashboard's Mini Remote drawer stays Remote-only. It is too narrow for the tabs, and its
Options menu points to the Mini Remote window instead.
- **The separate ILT Hub windows are gone.** Their saved open/closed flags
(`CharacterWindowOpen`, `PetsWindowOpen`, `QuestTrackerPoppedOut` and the rest) are ignored when
`ilt-hub.json` loads.
- The Games hand HUD and the quest favorites HUD still float on their own.
- The favorites HUD's "Open quest tracker" now switches the Mini Remote to its Quests tab.
- **Commands.**
- `/ra hub open <section> [show|hide|toggle]` switches the Mini Remote to that tab. It shows the
floating Mini Remote unless RynthCore's window already hosts it. `hide` goes back to Remote.
- `/ra hub tab <section>` only switches tabs. RynthCore's dashboard uses it after opening its
own Mini Remote window.
- **Guardian moved to RynthCore's ILT button.**
- The Temple guardian tools (riddle answers, Give, the phrasebook) draw in RynthCore's new
Guardian panel, through the new embed surface `"guardian"` (`RynthPluginRenderEmbed`).
- `/ra guardian window [show|hide|toggle]` and the Options menu's "Guardian panel" open that
panel through `/rc guardian`.
- The Mini Remote's "Guardian answer" section is unchanged.
- **RynthAi's own Bounties feature is removed.** RynthILT's Bounties panel (the ILT button,
`/rc bounties`) is the one bounty tracker.
- `/ra bounty ...` and `/ra hub open bounties` open that panel.
- The old `Bounty` block in `ilt-hub.json` is ignored on load.
- The `IltBounties` trace category is gone.
- **Wording.** Chat prefixes changed from `[ILT Hub]` to `[Mini Remote]`. The Settings tooltips
and the Server Features status line now say "Mini Remote" as well.
## Files
- `Huds/MiniRemoteHud.cs`: the tab bar (`RenderBody`) and the pending tab switch (`RequestTab`).
`BeginTab` calls `igBeginTabItem` with a null `p_open`, because ImGui.NET only wraps the flags
overload together with a close button. The Options menu's ILT group now links to the Guardian
and Bounties panels.
- `Huds/HudController.cs`: `HandleTabCommand(tab, mode)`.
- `Huds/HudState.cs`: `MiniRemoteTab`.
- `IltHub/IltSections.cs`: the tab list, tab ids and `IsTab`. Bounties was removed.
- `IltHub/IltHubUi.cs`: `TabSize`, `RenderTab` and `RenderGuardianPanel`. The per-section windows
were removed.
- `IltHub/IltHubController.cs`:
- `MiniRemoteTabCommand`, `OffersTabs`, `RenderTab`, `RenderGuardianPanel` and
`OpenEnginePanel`.
- The `tab` verb.
- Bounty and guardian-window verbs go to the engine panels.
- `IltHub/IltQuests.cs`: `RenderTab`. The popped-out tracker window was removed.
- `IltHub/IltHubContext.cs`: `ShowTab`.
- `IltHub/IltHubState.cs` and `IltHub/IltHubStore.cs`: the window flags and the bounty state were
removed.
- `IltHub/IltBounties.cs`, `IltHub/IltBountyParse.cs` and
`Tools/RynthCore.RynthAiHostTests/Tests/BountyTests.cs`: deleted.
- `PluginExports.cs`: the `"guardian"` embed surface.
- `RynthAiPlugin.LocalFeatures.cs`: `RenderEmbeddedGuardian` and the tab command wiring.
- `RynthAiPlugin.cs` and `Diagnostics/RynthLog.cs`: wording, and the `IltBounties` category was
removed.
- `LegacyUi/LegacyAdvancedSettingsUi.cs`, `IltHub/ServerFeatureGate.cs` and the other `IltHub/*`
files: wording.
## Testing
- Host tests: 613 of 614 pass. The one failure is the known map-bake test, which needs the real
dat files.
- In game, on an ILT world, check that:
- the tabs appear as features report on;
- the window refits per tab;
- the Char launcher opens the Character tab;
- the bar's ILT button lists Bounties and Guardian, and the Guardian panel draws the guardian
tools;
- `/ra hub open quests` switches tabs.

View file

@ -0,0 +1,41 @@
# RynthAi: one Mini Remote, resizable slots
## What changed
There were two Mini Remotes: RynthCore's own "Mini Remote" window (an empty grid of quick-launch
slots) and RynthAi's floating "MINI REMOTE" (stats, item grid, toggles, bank, rebuff, translate).
They are now one window.
- **The engine's Mini Remote window hosts RynthAi's remote.** It is the same window you get from
the bar button, `/rc miniremote`, or the dashboard's Hub launcher. It shows every RynthAi
section, Toggles included, and resizes itself to fit them.
- New embed surface `RynthPluginRenderEmbed("miniremote-window")`, next to the existing
`"miniremote"` (the dashboard drawer, which still leaves Toggles out).
- While that window shows the remote, RynthAi's floating copy stays hidden
(`HudController.MiniRemoteInEngineWindow`), so there is only ever one on screen.
`/ra remote` says where the remote is instead of opening a second one.
- In the window, the Options menu offers the Toggles section and leaves out "Floating window too".
- **Grow and shrink the slot boxes.**
- Ctrl+mouse wheel over the slot grid makes the boxes bigger or smaller, 2 px per notch.
- Options > "Slot size" slider (18-64 px) with a Default (28 px) button.
- Saved per character in `huds.json` as `MiniRemoteSlotSize`. Older files, which don't have
it, get the default.
- The columns, and the window or drawer around them, refit to the new size.
## Files
- `Huds/HudState.cs`: `MiniRemoteSlotSize` plus its range constants; clamped in `HudStore.Normalize`.
- `Huds/MiniRemoteHud.cs`: the slot size is read from state rather than a constant, plus
Ctrl+wheel, the Options slider and the `window` embed mode.
- `Huds/HudController.cs`: `RenderEmbedded(bool window)`, `MiniRemoteInEngineWindow`, the
floating window suppressed while the engine hosts the remote, and the `/ra remote` reply.
- `PluginExports.cs` and `RynthAiPlugin.LocalFeatures.cs`: the `"miniremote-window"` surface.
Needs the matching RynthCore engine (Mini Remote window host, same date). An older engine never
asks for `"miniremote-window"`, so with one this plugin behaves as before, apart from the
resizable slots.
## Tests
- RynthAi host tests: 619 tests, 618 passed. The one failure is the map bake (0x6346), which
already failed before this change.

View file

@ -0,0 +1,72 @@
# Navigation: Go To Closest Waypoint (on by default)
Pairs with the matching RynthCore commit on `sk`, which shows the option on the engine Settings page.
## Why
Navigation only looked for the closest waypoint at macro start. Two cases went the long way round:
- **After a pause:** combat, looting, buffing and doors stop nav, then hand back to it. Nav carried
on to the waypoint it was heading for before the pause, even when a chase had taken the
character next to a different part of the route. It walked back to the old waypoint first.
- **Already past the nearest point:** macro start picked the nearest waypoint even when the
character had just walked past it. Nav turned round to touch it, then turned back.
## What changed
- **New option: Advanced Settings > Navigation > Getting Back On Route > Go To Closest Waypoint.**
It is on by default. It is also on the engine Settings page under Navigation, and metas can read
or set it as `NavResumeNearest`.
- **With the option on:**
- **Macro start:** heads for the closest waypoint, as before.
- **Back from a pause that moved the character 10 yd or more:** re-picks the closest waypoint
instead of walking back to the old one. A pause that moved the character less than 10 yd
carries on to the same waypoint. A move of more than 400 yd counts as a teleport, which the
portal handling already deals with.
- **No turning back:** when the closest spot on the route is on the leg after the nearest
waypoint (the character already walked past it), nav heads for the next waypoint. A Linear
route follows its current direction. A step (recall, portal, chat, pause, NPC) is never
skipped to or over.
- **Loading a Circular or Linear route:** starts at its nearest waypoint, as before.
- Once routes still only look ahead of the current step, and Follow routes are not changed.
- A detour or area hold in progress keeps control, so the re-pick does not interrupt it.
- Indoors, macro start still compares the nearest waypoints by walking distance on the
dungeon map.
- **With the option off:**
- Pauses carry on to the waypoint nav was heading for.
- Macro start keeps the last waypoint.
- A loaded route starts at its first point.
- Hazard escapes and corpse runs still rejoin at the closest waypoint, because they take the
character off the route.
## Files
- `NavigationEngine.cs`:
- remembers where a pause started (`MarkPausePosition`);
- re-picks on the first steer tick back (`ResumeAfterPause`);
- `ResumeFromNearestWaypoint(bool always = false)` now honours the setting;
- `PassedToward` and `SegmentDistSq` implement the no-turning-back rule.
- `LegacyUiSettings.cs`: `NavResumeNearest` (default true), plus the engine DTO field (nullable,
so an absent value keeps the plugin's setting).
- `LegacyDashboardRenderer.cs`: engine round trip, `CopySettings`, and the route-load start index.
- `NavRouteParser.StartsAtFirstPoint`: the shared route-load rule, also used by
`MetaManager.StartIndexForRoute`.
- `LegacyAdvancedSettingsUi.cs`: the checkbox and its tooltip.
- `ExpressionEngine.cs`: the `NavResumeNearest` setting name for metas.
- `RynthAiPlugin.HazardEscape.cs`, `RynthAiPlugin.OwnCorpse.cs`: always rejoin at the closest
waypoint.
## Tests
`Tools/RynthCore.RynthAiHostTests`, 5 new tests:
- macro start skips a nearest waypoint already walked past, but not one still ahead;
- back from a pause that moved 10 yd or more, nav heads for the closest waypoint;
- back from a pause that moved less than 10 yd, nav keeps its waypoint;
- with the option off: the pause and macro-start cases keep the last waypoint, and hazard or
corpse rejoins still re-pick;
- the route-load start rule.
Result: 619 of 620 pass. The one failure is the known map-bake test, which needs local dats.
Not yet tested in game.

View file

@ -0,0 +1,46 @@
# RynthAi: fix the client crash when the Mini Remote (or Guardian) is popped out
Pairs with the matching RynthCore commit on `sk`, which carries the engine half of the fix.
## The crash
All four client crashes on 2026-10-11 between 21:32 and 21:38 (dumps
- The Application event log (.NET Runtime 1026) gives the stack:
- `ImGuiPopOuts.RenderAll`
- `ImGuiPanelHost.DrawPopped`
- `MiniRemoteFace.Draw`
- `PluginManager.RenderEmbed`
- an access violation inside coreclr
- The Mini Remote had been popped out into its own window, and RynthCore asked RynthAi to draw it
there.
- A popped-out panel has its own ImGui context. RynthAi's embedded surfaces always switched to
`Host.ImGuiContext`, the engine's main context, which isn't mid-frame at that point. ImGui
dereferenced a null current window, and an access violation can't be caught, so the client
died.
- It happened on the first frame the popped-out Mini Remote showed: the Char (hub) button's
left-click, or right after login when the window was left popped out.
- The 4 to 9 seconds of "MAIN THREAD HANG DETECTED" before each exit was the runtime writing the
crash dump, not a separate hang.
## Fix
- The embedded surfaces (`miniremote`, `miniremote-window`, `guardian`) draw in the context that
is current when RynthCore calls (`EmbedContext` in `RynthAiPlugin.LocalFeatures.cs`). That is
the window RynthCore has begun, whether it's docked or popped out.
- `RynthPluginRenderEmbed` accepts the names with a `:popout` suffix. the matching RynthCore
sends those from a pop-out so older RynthAi builds decline instead of crashing.
- With this build the popped-out Mini Remote and Guardian show RynthAi's own content.
## Files
- `PluginExports.cs`: strips the `:popout` suffix.
- `RynthAiPlugin.LocalFeatures.cs`: `EmbedContext`, used by `RenderEmbeddedMiniRemote` and
`RenderEmbeddedGuardian`.
## Testing
- Host tests: 616 of 617 pass. The one failure is the known map-bake test, which needs the real
dat files.
- Not yet checked in game: pop out the Mini Remote and the Guardian panel, use the Char button,
and log in with the Mini Remote left popped out.

View file

@ -0,0 +1,59 @@
# Recall On Death: cast a recall spell or use a recall item after dying
Pairs with the matching RynthCore commit on `sk`, which shows the option on the Settings page.
## What changed
- **New option: Settings > On Death > Recall On Death.** The choices are:
- Off (the default);
- Cast a recall spell: pick it from the nav editor's recall list (Primary Portal Recall by
default);
- Use a recall item: type the item's name as it shows in your inventory. An exact name wins;
otherwise the first item whose name contains it is used.
- **When it runs:**
- after you die while the macro is running;
- once you've respawned and the existing 5-second settle after the death portal is over;
- Stop Macro On Death still recalls first, because the recall is armed at the moment you die.
- **While it runs:**
- nothing else runs (no combat, buffing, looting or nav);
- a spell first gets a wand and magic mode, the same step a nav Recall waypoint takes;
- a fizzle or failed use is retried every 4 s for a spell and every 6 s for an item, up to
5 tries;
- once portal space or a landblock change shows the teleport happened, nothing more is fired.
- **Afterwards:**
- 3 s after landing, nav rejoins its route at the closest waypoint;
- Travel Back To My Corpse then starts from the landing spot. A Primary Portal Recall to your
hunting ground makes that walk much shorter.
- **Giving up:** after 5 tries or 60 s, it says why in chat and carries on from where you are.
- **Not started**, with a chat line saying why, when:
- the item isn't in your inventory;
- no item name is set;
- the engine can't cast or use items.
- Dying again during a recall cancels it.
## Files
- `DeathRecallRun.cs` (new): the attempt as a pure, clock-driven state machine: when to fire, when
the teleport counts as done, when to give up.
- `RynthAiPlugin.DeathRecall.cs` (new): armed on the death edge, started on the respawn edge,
ticked after the death hold; spell cast or item use, the chat report, then nav and the corpse
trip.
- `RynthAiPlugin.Safety.cs`, `RynthAiPlugin.cs`: wiring.
- `LegacyUiSettings.cs`: `DeathRecallMode`, `DeathRecallSpellId`, `DeathRecallItem`, plus the
engine DTO fields (nullable, so an older engine leaves them alone).
- `LegacyDashboardRenderer.cs`: engine round trip and `CopySettings`.
- `ExpressionEngine.cs`: the three setting names for metas.
## Tests
`Tools/RynthCore.RynthAiHostTests/Tests/DeathRecallTests.cs`, 5 new tests:
- fires at once, then retries every 4 s;
- portal space stops the firing, and the run is done 3 s after landing;
- a landblock change counts as the teleport;
- gives up after 5 tries, with items retried every 6 s;
- never fires while not ready, and times out after 60 s.
Result: 627 of 628 pass. The one failure is the known map-bake test, which needs local dats.
Not yet tested in game.

View file

@ -0,0 +1,99 @@
# Mini Remote and Tracker: one set of session-stat rules
RynthTracker 0.4.0 (previous: 0.3.0). Pairs with the matching RynthCore commit on `sk`, which adds the Tracker panel's new rows.
## Why
Before this release the Mini Remote and the Tracker panel computed the same stats with different code:
| Stat | Tracker (RynthTracker 0.3.0) | Mini Remote (RynthAi before) |
|---|---|---|
| Luminance | Character lum (6), plus Aelrynth's bank totals (9102 / 9103). On ACECustom it missed all banked lum and counted bank withdrawals as income. | ACECustom bank lum (9005) only, so it missed lum on retail ACE and on Aelrynth. |
| Kills | Kill notices, plus corpse kills from multi-target spells | Kill notices only |
| XP | Rises, polled every 0.5 s | Net change since the start, polled every 5 s |
| Worlds | All | ILT only ("Session stats: ILT worlds only") |
| Reload | The session carried over | The session started over |
| Lum in the last 5 minutes, pass-up | Neither tracked | Neither tracked |
## What changed
- **One shared engine:** `Plugins/Shared/SessionStats.cs` holds the rules, and
`Plugins/Shared/SessionStatsTracker.cs` feeds it from the game. Both plugins compile them in, so
every number below is computed the same way in both.
- **XP:** the rise of TotalExperience (1), read every 0.5 s.
- **Luminance, per server:**
- Retail ACE: the rise of AvailableLuminance (6).
- Aelrynth: as before, the Bank mod's auto-banked total (9102) added and its drawn total (9103)
taken out.
- ACECustom: the rise of BankedLuminance (9005). Once that property is read:
- rises of AvailableLuminance (6) are ignored, because there they are bank withdrawals;
- lum moved in by "Deposited N luminance" or "Received N luminance from X" is taken out of
the next bank rises (a line whose rise hasn't arrived within 60 s is dropped);
- "You've banked N Luminance." counts on its own only until a bank property (9005 or 9102)
is read.
- **Luminance in the last 5 minutes (new):** a rolling 5-minute window, kept in 5-second
buckets.
- **Pass-up (new):** ACECustom doesn't send the allegiance lum counters (9013 / 9014) to the
client. Pass-up is therefore bank income minus your own "You've banked" lines, because a
vassal's pass-up reaches the bank without a chat line. Fellowship and Zone Share splits also
arrive silently, so they are included. It is shown only where the bank is read (ACECustom).
- **Kills:** kill notices, plus corpse kills of monsters you hit with a multi-target spell
(`KillCounter`, moved to Shared).
- **XP per kill, deaths and Radiance:** unchanged from the Tracker.
- **Session lifecycle:** saved every 30 s and restored after a plugin reload (same client,
same character, saved within the last 10 minutes); a logout ends the session.
- RynthTracker saves to `%LOCALAPPDATA%\RynthCore\tracker`, the Mini Remote to
`%LOCALAPPDATA%\RynthCore\miniremote-stats`.
- Saves from RynthTracker 0.3.0 still load (the new keys are optional).
- **The Mini Remote's Stats section now works on every world:**
- It shows Time, XP/h, Lum/h, Lum 5m, Pass-up/h (ACECustom) and Kills/h, plus Coins/h and Pyr/h
on ILT.
- The Reset XP and Report buttons also work everywhere. Report now includes lum in the last
5 minutes and pass-up.
- **ILT Character tab "Session rates":**
- XP, Luminance, its last 5 minutes (with the per-hour pace), pass-up and Kills now come from
the shared stats.
- Coins, pyreals and item conversions are unchanged.
- The Reset button resets both the coin counts and the shared stats.
- **RynthTracker's snapshot JSON** gains these keys:
- `l5`: lum in the last 5 minutes;
- `pt`: pass-up total;
- `ph`: pass-up per hour;
- `pk`: 1 when pass-up is known.
The existing keys are unchanged.
- **Removed:** `IltLumIncome` and the `IltParse.LumBanked` regex. RynthAi's kill path no longer
calls `IltHubController.RecordKill`.
The Tracker panel and the Mini Remote each keep their own session and their own reset. They
match when both started at the same login; resetting one doesn't reset the other.
## Files
- `Plugins/Shared/SessionStats.cs` (new), `Plugins/Shared/SessionStatsTracker.cs` (new).
- `Plugins/Shared/KillCounter.cs`, `Plugins/Shared/TrackerSessionStore.cs`: moved from RynthTracker
into the `RynthCore.Plugin.Shared` namespace. The store adds `DirectoryFor` and the new save keys.
- `Plugins/RynthCore.Plugin.RynthTracker/RynthTrackerPlugin.cs`: a thin wrapper over the shared tracker, version 0.4.0.
- `Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs`, `RynthAiPlugin.LocalFeatures.cs`: own a
`SessionStatsTracker` and forward login, logout, shutdown, tick, chat, kill, object and health
events to it.
- `Plugins/RynthCore.Plugin.RynthAi/Huds/MiniRemoteHud.cs`, `Huds/HudController.cs`: universal Stats.
- `Plugins/RynthCore.Plugin.RynthAi/IltHub/IltSessionRates.cs`, `IltHubController.cs`, `IltParse.cs`.
- `Tools/RynthCore.TrackerSessionTests`: new `SessionStatsTests.cs`, covering:
- ILT bank lum, deposits, transfers, withdrawals and spending;
- pass-up;
- the chat fallback;
- Aelrynth and retail lum;
- the 5-minute window;
- kills and XP per kill;
- reload equivalence;
- parsing older saves.
- `Tools/RynthCore.RynthAiHostTests`: `LumIncomeTests` removed (it tested `IltLumIncome`).
## Testing
- TrackerSessionTests: 275 assertions, all pass.
- RynthAi host tests: 614 of 615 pass. The one failure is the known map-bake test, which needs
the dats.
- RynthAi and RynthTracker both publish as NativeAOT in Release.
- Not yet checked in game.

View file

@ -0,0 +1,65 @@
# SK RynthAi work through 2026-10-10, rebased on 2026.10.12.1
Replaces the closed per-feature PRs RynthSuite #2-#11 and the earlier `sk` commits. This commit
carries everything from those PRs that main doesn't already have, merged onto release 2026.10.12.1
with the conflicts resolved. Work from 2026-10-11 follows in separate commits.
`HandWrittenVersion` stays `0.5.0-legacy-ui`.
The merge-stack result the looter reads is engine API v81 now (rynth's 2026.10.12.1 took v80);
`HasGetMergeStackResult` in the SDK checks that, so an older engine just reports it unavailable.
## Needs a decision: item info
Both sides had `/ra iteminfo`. This commit keeps the Mag-Tools port (settings window, field and
rating toggles, click trigger, pet or line layout, T11 fields) and folds in rynth's additions:
- `/ra iteminfo <item name>` describes an inventory item by name.
- Items RynthAi selects itself (looter, meta `selectitem`) are not described.
- The line ends with the looter's verdict (`| Loot: [Keep] rule`), as a preview.
- The default prefix is `[RynthAi Item] `, so RynthChat files it under Items.
- Rynth's "Item Info On Select" checkbox, the meta setting `ItemInfoOnSelect` and the engine's
settings DTO drive `ItemInfoSettings.OnSelect`; an Options button opens the Item Info window.
To do that it **removes** rynth's `RynthAiPlugin.ItemInfo.cs`, `ItemInfo/ItemInfoText.cs` and
`Tests/ItemInfoTests.cs`. If rynth prefers his implementation, this is the part to drop.
## How the merge with 2026.10.11.1 was settled
- Rynth's side: pet essence refill-loop guard, typed-object filing (`WorldObjectCache`), spell
category and power (`SpellDatabase`), Decal synthetic keys, dungeon hazards, radar walls, meta
UI, and install paths (everything links `Plugins/Shared/RynthInstallPaths.cs`).
- Ours: the T11 loot catalog, keys and `/ra t11`, `LootItemRules`, the T11 loot tests, and
`RynthLog` categories in loot logging.
- Both: `LootRuleText` (rynth's text plus the T11 property keys and Gear Grade table), the
`MonsterEditor` JSON context, chat hooks, and the host test list.
## Features
- **ILT Hub** (`IltHub/`): character, quests, pets and pet stats, banking, gear and equip suits,
games, buff keepers, guardian answers, temple attributes, sigil chain, lum income, session
rates, USD import, and a server feature gate so ILT-only parts stay off elsewhere.
- **Attribute raiser and augmentation planner** with UB's InfiniteLeaftide cost math and
per-server cost settings (`IltAttributeRaiser`, `IltAugCosts`, `IltProgression`).
- **HUDs** (`Huds/`): Mini Remote, combat HUD and item count HUD, with an icon cache.
- **Item info** as above (`MagItemDescriber`, `MagItemInfoSettings`, `LegacyItemInfoUi`).
- **Chat translation** (`Translate/`): per-channel auto-translation with its own settings UI.
- **Ground loot** (`GroundLootController`).
- **Nav:** route editing in the dashboard, breadcrumbs, and a route overlay
(`NavRouteEditing`, `NavBreadcrumbTracker`, `NavOverlayRenderer`).
- **Spells:** a spell catalog generated from the client's spell table
(`SpellCatalog.tsv`, `Tools/Generate-SpellCatalog.ps1`), buff profiles, and a Spells window.
- **Creature data:** UB's damage seed in the Auto element ranking (`Shared/UbMobSeed.cs`,
`UbMobSeedStore`), and VirindiTank profile and USD monster imports (plugin and Monster Editor).
- **Loot:** the ACECustom T11 item state for item ID and loot rules; "Include T11 attributes"
when adding an item to a loot profile; unknown VTank conditions bounded by their length code.
- **Corpses:** only the "Killed by" line names the killer.
- **Diagnostics:** per-category, per-process RynthAi log files (`Diagnostics/RynthLog.cs`).
- **Plumbing:** the plugin calls cimgui through its own binding (`ImGuiNativeBinding`), window
placement helpers (`UiPlacement`), and the plugin exports the engine's overlay, embed and remote
commands use (`PluginExports`).
## Testing
- `dotnet build -c Release`: RynthAi plugin and Monster Editor.
- LootSdkTests pass.
- RynthAiHostTests pass except the map bake, which needs the real dat files on the test machine.

View file

@ -0,0 +1,50 @@
# RynthAi: Quests and Pets on every server; "Server: <name>" in the right-click menu
Pairs with the matching RynthCore commit on `sk`.
## What changed
- **Quests and Pets are universal.**
- They were Infinite Leaftide tabs. Now they show on every server, in every Mini Remote: the
floating window, RynthCore's Mini Remote window, and that window popped out.
- The tab bar runs: Remote, Quests, Pets. On ILT worlds the ILT tabs follow: Character,
Banking, Gear, Games.
- The quest tracker (`/myquests`) and the pet roster, priorities and healing pet tick and read
chat on every world (`IltHubController.IsUniversal`).
- The ILT-only parts of those tabs show only on ILT worlds:
- Quests: the quest bonus list (`/qb`).
- Pets: the Summon Essence Refill and Universal Summoning Mastery charms, and the `/pets` and
`/shinies` logs.
- **Guardian stays ILT only.** It's still RynthCore's ILT panel, listed under the server section.
- **Right-click menu:**
- Top: **Character**, with Spells, Quests, Pets, Skills, Inventory, Item Count and Inventory
HUDs setup.
- Bottom: **Server: <server name>** (e.g. "Server: Infinite Leaftide"), with the installed
server plugins' windows. For ILT that's the Character, Banking, Gear and Games tabs,
Guardian, Bounties and Progression.
- With an older RynthCore that still lists Quests and Pets under the server, they are left out
there so they don't show twice.
## Files
- `IltHub/IltSections.cs`: the tab order (universal first) and `IsUniversal`.
- `IltHub/IltHubController.cs`:
- `SectionAvailable`: Quests and Pets are always available;
- new `TabShown`;
- universal features tick and read chat on every world.
- `IltHub/IltPets.cs`, `IltHub/IltQuests.cs`: the ILT-only parts are gated on an ILT world.
- `Huds/MiniRemoteHud.cs`:
- the tab bar (`TabShown`);
- Quests and Pets under Character;
- the "Server: " header;
- universal tabs skipped in the server section.
- `Tools/RynthCore.RynthAiHostTests/Tests/ServerMenuTests.cs`: a universal-tabs test.
## Testing
- Host tests: 617 of 618 pass. The one failure is the known map-bake test, which needs the real
dat files. The new universal-tabs test passes.
- Not yet checked in game:
- Quests and Pets tabs on a non-ILT world;
- the "Server: Infinite Leaftide" section on ILT;
- no `/qb`, `/pets` or `/shinies` being sent off ILT.

View file

@ -0,0 +1,23 @@
# RynthNet 0.1.1: object id and combat mode in the shared status
Pairs with the RynthCore engine's Characters panel (`/rc characters`, RynthCore
`feature/characters-panel`).
## What changed
- Each client's shared status (sent every `statusIntervalMs`) now has two more fields:
- `id`: the character's object id. It is the same on every client, so the Characters panel can
select that character with a click when it is in view.
- `cmode`: AC's combat mode (1 peace, 2 melee, 4 missile, 8 magic). The panel shows a stance
when the macro is off.
- The fields are optional. A 0.1.0 client's status simply lacks them, and readers treat every
status field as optional.
- `Docs/RYNTHNET.md` now lists the fields and points to the Characters panel as the NetworkUI HUD.
## Files
- `RynthNetPlugin.Status.cs`: the two fields. `cmode` is written only when the host has
`GetCurrentCombatMode`, which reads a cached value off AC's thread.
- `RynthNetPlugin.cs`: version 0.1.1.
Not yet tested in game.

View file

@ -0,0 +1,206 @@
// ============================================================================
// RynthSuite - Plugins/RynthCore.Plugin.RynthAi/Combat/BuffCastChain.cs
// Buff cast chaining: the next buff of a pass goes out on the last buff's UseDone,
// without waiting for the client to finish playing the cast's recoil.
//
// Why: in a buff pass every buff waited on the animation gate (ActionPacer.GestureHolds
// and CastGateWatchdog.CanCastNow, both the client's CMotionInterp queue) after the
// server's UseDone for the previous buff: "[Pace] Buff waits: the character is still
// animating" after each UseDone, and the next buff ~550 ms later (UseDone to next buff:
// median 553 ms over 74 buffs, bimodal at ~50 and ~550 ms). On ACE the server clears
// IsBusy just before it sends that UseDone (Player_Magic.cs: IsBusy = false;
// SendUseDoneEvent()), and VerifyBusy only checks IsBusy, so it takes the next cast at
// once; the client is still showing the recoil the server already finished.
//
// The fast path (LegacyUiSettings.FastBuffChain, default on) opens ONLY the animation
// gate, and only when all of these hold:
// * the last action RynthAi sent was one of BuffManager's own buff casts
// (ActionPacer.Started and AttacksSent unchanged since it went out);
// * the very next UseDone after it is the last one (no other UseDone since) and its
// error is 0;
// * that UseDone was seen less than WindowMs ago;
// * no movement call reached the client since the buff went out (MoveAudit.MovementSends
// unchanged): a stop, a start or a turn starts a motion the client still has to play, so
// the next buff waits on the animation gate for it (a buff went out 50 ms after a nav stop);
// * no refusal has turned the fast path off for this buff pass.
// Every other gate stays: the pacer's outstanding-action gate, the pending cast, the
// server-resolution wait, the busy count, the cast interval, the stance (EnsureMagicMode),
// the mana floor, the too-busy backoff. BuffManager also takes the fast path only while
// no vital is under any of its lines (the mana reserve included), and drops it for a buff
// that would need Stamina to Mana first, so no kit, potion or vital cast rides it.
//
// Refusals (the crash this protects against: a tight retry loop on "You're too busy!"
// re-enters AC's AddTextToScroll -> AV 0x00460D1D, see BuffManager.OnChatWindowText and
// CastGateWatchdog): the throttle, the park and the escalating backoff are untouched, and
// any refusal of a buff cast that went out on the fast path (the client's CastSpell
// returning false, a "too busy" line for it, or an error in its UseDone) turns the fast
// path off for the rest of the pass, logged. Every refusal during buffing is counted for
// as a running total since load, logged one line each, and each pass ends with a summary line.
// ============================================================================
using System;
namespace RynthCore.Plugin.RynthAi;
internal sealed class BuffCastChain
{
/// <summary>The fast path is only taken this long after the last buff's UseDone was seen.</summary>
public const double WindowMs = 1500;
// The last buff cast BuffManager sent.
private int _spellId;
private string _name = "";
private int _seqAtSend;
private long _startedAfter;
private long _attacksAfter;
private long _movesAfter;
private bool _moveCounted; // MovementWaits counted for this send
private bool _wasFast;
private bool _heldForAnimation; // the next buff goes through the animation gate (HoldForAnimation)
private bool _answerSeen; // the first UseDone after it was read
private bool _answerOk; // ... and it was UseDone(0), the next UseDone after the send
private DateTime _answerSeenAt = DateTime.MinValue;
// This pass.
private bool _inPass;
private bool _offThisPass;
private int _passCasts, _passFast, _passClient, _passServer, _passTooBusy;
// Running totals since load.
public int ClientRefusals { get; private set; }
public int ServerRefusals { get; private set; }
public int TooBusyLines { get; private set; }
public int FastCasts { get; private set; }
public int BuffCasts { get; private set; }
public int PassesSwitchedOff { get; private set; }
/// <summary>Times the fast path was refused because a movement call went out after the last buff.</summary>
public int MovementWaits { get; private set; }
/// <summary>True when a refusal turned the fast path off for the rest of this pass.</summary>
public bool OffThisPass => _offThisPass;
public bool InPass => _inPass;
public void PassStart()
{
if (_inPass) return;
_inPass = true;
_offThisPass = false;
_passCasts = _passFast = _passClient = _passServer = _passTooBusy = 0;
}
/// <summary>The pass is over (complete or cancelled): one summary line.</summary>
public void PassEnd(string how, Action<string> log)
{
if (!_inPass) return;
_inPass = false;
log($"[BuffChain] buff pass {how}: {_passCasts} buff cast(s), {_passFast} on the fast path" +
$"{(_offThisPass ? " (fast path switched off by a refusal)" : "")}; refusals this pass: client {_passClient}, " +
$"server {_passServer}, too-busy lines {_passTooBusy}; totals: client {ClientRefusals}, server {ServerRefusals}, " +
$"too-busy lines {TooBusyLines}, {FastCasts} of {BuffCasts} buff casts on the fast path");
_offThisPass = false;
}
/// <summary>A buff cast went out. <paramref name="seqAtSend"/> is the UseDone count read before the send;
/// <paramref name="started"/> / <paramref name="attacks"/> are ActionPacer's counts and <paramref name="moves"/>
/// MoveAudit.MovementSends, all read after it.</summary>
public void Sent(int spellId, string name, int seqAtSend, long started, long attacks, long moves, bool fast)
{
_spellId = spellId;
_name = name;
_seqAtSend = seqAtSend;
_startedAfter = started;
_attacksAfter = attacks;
_movesAfter = moves;
_moveCounted = false;
_wasFast = fast;
_heldForAnimation = false;
_answerSeen = false;
_answerOk = false;
_answerSeenAt = DateTime.MinValue;
BuffCasts++;
_passCasts++;
if (fast) { FastCasts++; _passFast++; }
}
/// <summary>The client refused a buff cast (CastSpell returned false: nothing went out).</summary>
public void ClientRefused(int spellId, string name, bool fast, Action<string> log)
{
ClientRefusals++;
_passClient++;
log($"[BuffChain] refusal (client): CastSpell refused '{name}' (id {spellId}){(fast ? " on the fast path" : "")}" +
$" - totals client {ClientRefusals}, server {ServerRefusals}, too-busy lines {TooBusyLines}");
if (fast) SwitchOff("the client refused a fast-path cast", log);
_spellId = 0; // nothing went out: nothing to chain on
}
/// <summary>
/// Each tick: reads the first UseDone after the last buff cast. An error in it is a server refusal
/// (counted, logged; on the fast path the fast path is off for the pass).
/// </summary>
public void Observe(bool hasLast, int lastSeq, uint lastErr, int seqNow, DateTime now, Action<string> log)
{
if (_spellId == 0 || _answerSeen || !hasLast) return;
if (lastSeq <= _seqAtSend) return; // not answered yet
_answerSeen = true;
_answerSeenAt = now;
bool next = lastSeq == _seqAtSend + 1 && seqNow == lastSeq;
_answerOk = next && lastErr == 0;
if (next && lastErr != 0)
{
ServerRefusals++;
_passServer++;
log($"[BuffChain] refusal (server): UseDone error 0x{lastErr:X} for '{_name}'{(_wasFast ? " on the fast path" : "")}" +
$" - totals client {ClientRefusals}, server {ServerRefusals}, too-busy lines {TooBusyLines}");
if (_wasFast) SwitchOff($"the server refused a fast-path cast (0x{lastErr:X})", log);
}
}
/// <summary>A "You're too busy!" line while <paramref name="pendingSpellId"/> (a buff of ours) waited for its result.</summary>
public void TooBusyLine(int pendingSpellId, Action<string> log)
{
if (!_inPass || pendingSpellId == 0) return;
TooBusyLines++;
_passTooBusy++;
bool ours = pendingSpellId == _spellId;
log($"[BuffChain] refusal (too-busy line) while '{(ours ? _name : $"spell {pendingSpellId}")}' was pending" +
$"{(ours && _wasFast ? " (sent on the fast path)" : "")} - totals client {ClientRefusals}, server {ServerRefusals}, too-busy lines {TooBusyLines}");
if (ours && _wasFast) SwitchOff("a fast-path cast drew 'You're too busy!'", log);
}
/// <summary>The next buff needs another cast first (Stamina to Mana for the mana reserve): no fast
/// path until the next buff cast goes out.</summary>
public void HoldForAnimation() => _heldForAnimation = true;
private void SwitchOff(string why, Action<string> log)
{
if (_offThisPass) return;
_offThisPass = true;
PassesSwitchedOff++;
log($"[BuffChain] {why}: the next buffs of this pass wait for the animation again");
}
/// <summary>
/// May the next buff skip the animation gate? <paramref name="why"/> says why it may (for the log).
/// The caller has checked the setting, the pacing and the vitals.
/// </summary>
public bool Eligible(long started, long attacks, long moves, bool hasLast, int lastSeq, uint lastErr, int seqNow, DateTime now, out string why)
{
why = "";
if (_offThisPass || _heldForAnimation || _spellId == 0 || !_answerSeen || !_answerOk) return false;
if (started != _startedAfter || attacks != _attacksAfter) return false; // something else went out since
if (!hasLast || lastSeq != _seqAtSend + 1 || seqNow != lastSeq || lastErr != 0) return false; // another UseDone since
double age = (now - _answerSeenAt).TotalMilliseconds;
if (age > WindowMs) return false;
if (moves != _movesAfter) // a stop, start or turn went out since: its motion must play first
{
if (!_moveCounted) { _moveCounted = true; MovementWaits++; }
return false;
}
why = $"'{_name}' answered UseDone(0) {age:0} ms ago";
return true;
}
public string Describe() =>
$"Buff chain: {FastCasts} of {BuffCasts} buff casts on the fast path; refusals client {ClientRefusals}, " +
$"server {ServerRefusals}, too-busy lines {TooBusyLines}; passes switched off {PassesSwitchedOff}; movement waits {MovementWaits}";
}

View file

@ -0,0 +1,131 @@
using System;
using System.Collections.Generic;
using System.IO;
namespace RynthCore.Plugin.RynthAi;
/// <summary>
/// Buff profiles (Spells window / Loaded Files → Buffs): when one is chosen, its enabled
/// spells replace the built-in buff list, in the profile's order. Each entry is a base name
/// ("Strength Self") resolved to the best tier the character knows like the built-in list;
/// spells without a tier ladder (server-custom or lore names) fall back to the best known
/// spell of the same ACE spell family.
/// </summary>
public partial class BuffManager
{
// Re-checking the file's timestamp every call would hit the disk ~30x a second.
private const int BuffProfileRecheckMs = 3000;
private string _buffProfilePath = string.Empty;
private DateTime _buffProfileWriteUtc;
private long _buffProfileCheckedAt = long.MinValue / 2;
private List<string>? _profileKeys;
private readonly Dictionary<string, BuffProfileEntry> _profileByKey = new(StringComparer.OrdinalIgnoreCase);
/// <summary>Name of the buff profile in use, or null when buffing uses its built-in list.</summary>
public string? ActiveBuffProfileName { get; private set; }
/// <summary>Spells (enabled entries) in the active buff profile; 0 with no profile.</summary>
public int ActiveBuffProfileCount => _profileKeys?.Count ?? 0;
/// <summary>
/// Follows <see cref="LegacyUiSettings.CurrentBuffProfilePath"/>: loads the profile when the
/// path changes or the file is re-saved (the Spells window's Save), drops it when the path is
/// cleared. A missing or unreadable file means the built-in list, with one chat line.
/// </summary>
private void SyncBuffProfile()
{
string path = _settings.CurrentBuffProfilePath ?? string.Empty;
long now = Environment.TickCount64;
bool pathChanged = !path.Equals(_buffProfilePath, StringComparison.OrdinalIgnoreCase);
if (!pathChanged && now - _buffProfileCheckedAt < BuffProfileRecheckMs) return;
_buffProfileCheckedAt = now;
if (path.Length == 0)
{
if (pathChanged) ClearBuffProfile("[RynthAi] Buffing: built-in buff list.");
_buffProfilePath = path;
return;
}
DateTime writeUtc;
try { writeUtc = File.Exists(path) ? File.GetLastWriteTimeUtc(path) : DateTime.MinValue; }
catch { writeUtc = DateTime.MinValue; }
if (!pathChanged && writeUtc == _buffProfileWriteUtc) return;
_buffProfilePath = path;
_buffProfileWriteUtc = writeUtc;
SpellCatalog.EnsureLoaded(m => _host.Log(m));
if (!BuffProfileStore.TryLoad(path, out BuffProfile profile, out string error))
{
ClearBuffProfile($"[RynthAi] Buff profile '{Path.GetFileNameWithoutExtension(path)}' could not be read ({error}) - using the built-in buff list.");
return;
}
ApplyBuffProfile(profile);
_host.WriteToChat($"[RynthAi] Buffing: profile '{profile.Name}' ({ActiveBuffProfileCount} spell(s)).", 5);
}
/// <summary>Uses <paramref name="profile"/>'s enabled entries as the buff list (tests call this directly).</summary>
internal void ApplyBuffProfile(BuffProfile profile)
{
_profileByKey.Clear();
var keys = new List<string>(profile.Entries.Count);
foreach (var e in profile.Entries)
{
if (!e.Enabled || string.IsNullOrWhiteSpace(e.Key)) continue;
// One cast per base name: two tiers of the same line would fight over one family.
if (_profileByKey.ContainsKey(e.Key)) continue;
_profileByKey[e.Key] = e;
keys.Add(e.Key);
}
_profileKeys = keys;
ActiveBuffProfileName = profile.Name;
}
private void ClearBuffProfile(string chatLine)
{
bool had = _profileKeys != null;
_profileKeys = null;
_profileByKey.Clear();
ActiveBuffProfileName = null;
if (had || chatLine.Contains("could not be read", StringComparison.Ordinal))
_host.WriteToChat(chatLine, 5);
}
/// <summary>The active profile's base names, or null to use the built-in list.</summary>
private List<string>? ProfileBuffList()
{
SyncBuffProfile();
return _profileKeys is { Count: > 0 } keys ? new List<string>(keys) : null;
}
/// <summary>Casting skill for a buff: the catalog school for profile spells, else by name.</summary>
internal AcSkillType SkillFor(string baseName) =>
_profileByKey.TryGetValue(baseName, out var e) && e.School.Length > 0
? SpellCatalog.SkillForSchool(e.School)
: SkillForBuff(baseName);
/// <summary>
/// Profile spells whose base name has no tier ladder: the best spell of the same family the
/// character knows, capped by the buffing tier for its skill. Self and item spells win over
/// Other ones at the same level. 0 when the spellbook snapshot is cold or nothing is known.
/// </summary>
private int ResolveProfileFallback(string baseName, AcSkillType skill)
{
if (!_profileByKey.TryGetValue(baseName, out var entry) || !_spellManager.IsKnownSnapshotWarm) return 0;
int maxTier = _spellManager.GetHighestBuffSpellTier(skill);
SpellCatalogEntry? best = null;
foreach (var c in SpellCatalog.Family(entry.FamilyId))
{
if (!c.IsBuff || c.Level > maxTier || !_spellManager.IsKnownSpellId(c.Id)) continue;
if (best == null || Rank(c) > Rank(best)) best = c;
}
if (best != null) return best.Id;
// Family unknown to the catalog: the exact spell picked in the Spells window.
return entry.SpellId != 0 && _spellManager.IsKnownSpellId(entry.SpellId) ? entry.SpellId : 0;
static long Rank(SpellCatalogEntry c) =>
(long)c.Level * 1_000_000 + (c.IsSelf || c.IsItemTarget ? 100_000 : 0) + c.Power;
}
}

View file

@ -0,0 +1,266 @@
// ============================================================================
// RynthSuite - Combat/BuffManager.HpFailsafe.cs
// The HP failsafe: at or under Emergency Heal At, a character whose heals keep
// failing (refused, fizzled, never sent, or out-healed) must not sit and die.
//
// Measured by health, not by counting heal attempts: a round of FailsafeRoundMs
// with no rise of FailsafeRiseMinPct counts as a failed round (whatever the
// reason: a stuck cast, 'too busy', no mana, no kits).
// 1. FailsafeRoundsToBreak failed rounds: ActionPacer.ForceBreak (a jump; on
// ACE's fast tick it fails the cast in progress, Player.HandleActionJump).
// Starts are held until landed, then the vitals step heals again.
// 2. FailsafeRoundsToRecall more failed rounds after the break: recall to the
// lifestone ("/lifestone", ACE GameAction TeleToLifestone) when
// HpFailsafeRecall is on. The macro is switched off first, because ACE
// cancels the recall when the character moves during its animation and
// refuses it while busy (Player_Location.HandleActionTeleToLifestone).
// 3. No "<our name> is recalling to the lifestone." after RecallMaxSends tries
// (ACE refuses the recall while busy, under a PK timer or with recalls
// disabled, which is just the stuck state this is for): the macro is
// switched back on, so the heals and kits run again, and the failsafe
// re-arms; the next recall waits RecallCooldownMs. A failed recall must not
// leave the character standing at low health with nothing running. Only a
// macro the failsafe itself stopped is switched back on, never past a VTank
// yield (MayRestartMacro), and a death drops the pending recall (the player's
// Stop Macro On Death stands).
// Health back over the line (or 100%) ends the episode. Nothing counts in portal space.
// ============================================================================
using System;
using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthAi;
public partial class BuffManager
{
internal const double FailsafeRoundMs = 2500;
internal const int FailsafeRoundsToBreak = 3;
internal const int FailsafeRoundsToRecall = 3;
// A rise this large (health %) means a heal landed; natural regeneration is smaller.
private const int FailsafeRiseMinPct = 3;
// The recall goes this long after the macro stop (the stop edge runs on the next tick),
// and is sent again this often, a few times, until our "is recalling to the lifestone" is seen.
private const double RecallFirstDelayMs = 600;
private const double RecallResendMs = 1500;
private const int RecallMaxSends = 3;
/// <summary>After a recall that never started, the next one waits this long (the heals run meanwhile).</summary>
internal const double RecallCooldownMs = 30_000;
internal const string RecallCommand = "/lifestone";
private bool _fsActive;
private DateTime _fsRoundStart;
private int _fsLowHp;
private int _fsFailedRounds;
private bool _fsBroken;
private bool _fsRecallLogged;
private DateTime _fsRecallNotBefore = DateTime.MinValue;
private bool _recallPending;
private bool _recallSeen;
private int _recallSends;
private DateTime _recallNextAt;
/// <summary>Set by the plugin: the rest of a /ra stop (nav stop, pause cancel) for the recall.</summary>
internal Action? MacroStopForRecall { get; set; }
/// <summary>Set by the plugin: false when the macro must not be started now (VTank yield). Null = may.</summary>
internal Func<bool>? MayRestartMacro { get; set; }
// The macro is off because the failsafe stopped it for a recall (only then does it switch it back on).
private bool _macroStoppedByFailsafe;
private bool _recallNameLogged;
internal int HpFailsafeBreaks { get; private set; }
internal int HpFailsafeRecalls { get; private set; }
internal int HpFailsafeRecallsFailed { get; private set; }
private bool Portaling()
{
try { return _host.HasIsPortaling && _host.IsPortaling(); } catch { return false; }
}
/// <summary>Once per heartbeat while the macro runs, before the pacing gate.</summary>
private void TickHpFailsafe()
{
int at = _settings.EmergencyHealAt;
if (at <= 0 || _vitals.MaxHealth <= 0 || _recallPending || Portaling()) { ResetHpFailsafe(); return; }
int hp = _vitals.HealthPct;
DateTime now = Now;
if (hp > at || hp >= 100)
{
if (_fsActive && (_fsFailedRounds > 0 || _fsBroken))
_host.Log($"[Vitals] HP failsafe: health back to {hp}% (over Emergency Heal At {at}%).");
ResetHpFailsafe();
return;
}
if (!_fsActive)
{
_fsActive = true;
_fsRoundStart = now;
_fsLowHp = hp;
_fsFailedRounds = 0;
_fsBroken = false;
return;
}
if (hp >= _fsLowHp + FailsafeRiseMinPct)
{
// A heal landed: the heals work, start counting again from here.
_fsLowHp = hp;
_fsRoundStart = now;
_fsFailedRounds = 0;
return;
}
if (hp < _fsLowHp) _fsLowHp = hp;
if ((now - _fsRoundStart).TotalMilliseconds < FailsafeRoundMs) return;
_fsFailedRounds++;
_fsRoundStart = now;
double failedSec = _fsFailedRounds * FailsafeRoundMs / 1000.0;
if (!_fsBroken)
{
if (_fsFailedRounds < FailsafeRoundsToBreak) return;
string why = $"HP failsafe: health {hp}% at or under Emergency Heal At {at}%, no heal landed in {failedSec:0.#} s";
bool jumped = ActionPacer.ForceBreak(_host, why);
if (jumped) HpFailsafeBreaks++;
_host.Log($"[Vitals] {why}: {(jumped ? "breaking the cast with a jump, then healing again" : "no jump available (or one under way), healing again")}.");
_fsBroken = true;
_fsFailedRounds = 0;
return;
}
if (_fsFailedRounds < FailsafeRoundsToRecall) return;
if (!_settings.HpFailsafeRecall)
{
if (!_fsRecallLogged)
{
_fsRecallLogged = true;
_host.Log($"[Vitals] HP failsafe: health {hp}%, heals still failing {failedSec:0.#} s after the break; HP Failsafe Recall is off, no recall.");
}
return;
}
if (now < _fsRecallNotBefore)
{
// The last recall never started: heal on and break again, the next recall after the cooldown.
_fsBroken = false;
_fsFailedRounds = 0;
return;
}
StartFailsafeRecall(now, hp, failedSec);
}
private void ResetHpFailsafe()
{
_fsActive = false;
_fsFailedRounds = 0;
_fsBroken = false;
_fsRecallLogged = false;
}
private void StartFailsafeRecall(DateTime now, int hp, double failedSec)
{
HpFailsafeRecalls++;
_settings.IsMacroRunning = false;
_macroStoppedByFailsafe = true;
_recallNameLogged = false;
MacroStopForRecall?.Invoke();
_recallPending = true;
_recallSeen = false;
_recallSends = 0;
_recallNextAt = now.AddMilliseconds(RecallFirstDelayMs);
string line = $"HP failsafe: health {hp}%, heals still failing {failedSec:0.#} s after the break: macro stopped, recalling to the lifestone.";
_host.Log("[Vitals] " + line);
_host.WriteToChat("[RynthAi] " + line, 2);
ResetHpFailsafe();
}
/// <summary>Every heartbeat, macro running or not: sends a pending recall, or gives up on it.</summary>
private void TickFailsafeRecall()
{
if (!_recallPending) return;
DateTime now = Now;
if (_recallSeen)
{
_recallPending = false;
_macroStoppedByFailsafe = false;
_host.Log("[Vitals] HP failsafe: the recall started.");
return;
}
if (_vitals.MaxHealth > 0 && _vitals.CurrentHealth == 0)
{
CancelPendingRecall("dead");
return;
}
if (_settings.IsMacroRunning)
{
// Someone switched the macro back on: their call, the recall is dropped.
_recallPending = false;
_macroStoppedByFailsafe = false;
_host.Log("[Vitals] HP failsafe: the macro was started again; the recall is dropped.");
return;
}
if (now < _recallNextAt) return;
if (_recallSends >= RecallMaxSends || !_host.HasInvokeChatParser)
{
_recallPending = false;
HpFailsafeRecallsFailed++;
_fsRecallNotBefore = now.AddMilliseconds(RecallCooldownMs);
string why = _host.HasInvokeChatParser
? $"no recall seen after {_recallSends} tries of {RecallCommand} (refused: busy, a PK timer or recalls disabled)"
: "this engine has no chat parser, so no recall";
string what;
if (!_macroStoppedByFailsafe) what = "the macro stays as it is";
else if (MayRestartMacro != null && !MayRestartMacro()) what = "the macro stays off (VTank yield)";
else
{
_settings.IsMacroRunning = true; // the heals and kits run again; the failsafe re-arms
what = "macro back on to keep healing";
}
_macroStoppedByFailsafe = false;
string line = $"HP failsafe: {why}: {what}; next recall in {RecallCooldownMs / 1000:0} s at the earliest.";
_host.Log("[Vitals] " + line);
_host.WriteToChat("[RynthAi] " + line, 2);
return;
}
_host.InvokeChatParser(RecallCommand);
_recallSends++;
_recallNextAt = now.AddMilliseconds(RecallResendMs);
}
/// <summary>
/// The plugin's death hold (and a 0-health read): a pending recall is dropped and the macro is
/// left off, so nothing re-sends /lifestone or restarts the macro after the respawn.
/// </summary>
internal void CancelPendingRecall(string why)
{
if (!_recallPending) return;
_recallPending = false;
_macroStoppedByFailsafe = false;
_host.Log($"[Vitals] HP failsafe: the pending recall is dropped ({why}); the macro stays off.");
}
/// <summary>OnChatWindowText: "<our name> is recalling to the lifestone." while a recall is pending.</summary>
private void ObserveRecallLine(string lower)
{
if (!_recallPending || !lower.Contains("is recalling to the lifestone")) return;
string me = "";
try
{
uint id = unchecked((uint)_host.GetPlayerId());
if (id != 0 && _host.HasGetObjectName && _host.TryGetObjectName(id, out string n)) me = n ?? "";
}
catch { me = ""; }
// Someone else's recall ("Bob is recalling to the lifestone.") is not ours. The chat layer
// can drop a line's first letter ("ou cast ..."), so the name may arrive without it.
if (me.Length > 0)
{
string who = lower.Substring(0, lower.IndexOf(" is recalling to the lifestone", StringComparison.Ordinal)).Trim();
string mine = me.ToLowerInvariant();
bool ours = who == mine || (who.Length == mine.Length - 1 && who.Length > 0 && mine.EndsWith(who, StringComparison.Ordinal));
if (!ours) return;
}
else if (!_recallNameLogged)
{
_recallNameLogged = true;
_host.Log("[Vitals] HP failsafe: our name could not be read; any 'is recalling to the lifestone' line is taken as ours.");
}
_recallSeen = true;
}
}

View file

@ -0,0 +1,98 @@
// ============================================================================
// RynthSuite - Combat/BuffManager.Recharge.cs
// Recharge (VTank's "Recharge" hotkey, /ra recharge): one vitals pass now, with
// the current settings, whether the macro runs or not.
//
// The pass is CheckVitals with the idle lines (Top Off HP / Top Off Stam / Top
// Off Mana) whatever is in range, so a character between fights tops off now
// instead of waiting for the next idle moment; the emergency lines still come
// first. It uses what the vitals step uses (kits, Heal Self / Revitalize /
// Stamina to Mana, listed potions; Stamina to Health at its own line) and does
// one thing: a heal, a stamina or a mana recharge. Nothing under a line: it says
// so and does nothing.
//
// Requested from any thread (chat commands run on AC's thread); the pass runs on
// the next heartbeat (pump thread) once the server has answered the last action
// and no cast or kit is in flight, waiting up to RechargeWaitMs.
// ============================================================================
using System;
using System.Threading;
namespace RynthCore.Plugin.RynthAi;
public partial class BuffManager
{
internal const long RechargeWaitMs = 5000;
private int _rechargeRequested;
private long _rechargeRequestedAt;
/// <summary>Asks for one recharge pass on the next heartbeat. Any thread.</summary>
public void RequestRecharge()
{
Interlocked.Exchange(ref _rechargeRequestedAt, Environment.TickCount64);
Interlocked.Exchange(ref _rechargeRequested, 1);
}
/// <summary>A requested pass is waiting to run.</summary>
internal bool RechargePending => Volatile.Read(ref _rechargeRequested) != 0;
/// <summary>HeartbeatCore, every tick (macro on or off): runs a requested pass when the character is free.</summary>
private void TickRechargeRequest()
{
if (Volatile.Read(ref _rechargeRequested) == 0) return;
long waited = Environment.TickCount64 - Interlocked.Read(ref _rechargeRequestedAt);
string busy = RechargeBusyReason();
if (busy.Length > 0)
{
if (waited < RechargeWaitMs) return;
Interlocked.Exchange(ref _rechargeRequested, 0);
_host.WriteToChat($"[RynthAi] Recharge: not done, the character stayed busy ({busy}).", 1);
return;
}
Interlocked.Exchange(ref _rechargeRequested, 0);
_host.WriteToChat("[RynthAi] Recharge: " + RechargeOnceNow(), 1);
}
/// <summary>What holds a recharge pass back right now ("" = nothing).</summary>
private string RechargeBusyReason()
{
if (_vitals.MaxHealth <= 0) return "vitals not read yet";
if (_pendingSpellId != 0) return "a cast is in flight";
if (KitPending()) return "a kit is in flight";
if (!PacerAllows(out string why)) return "server answering the last action: " + why;
if (!CastGateWatchdog.CanCastNow(_host.CanCastNow, s => _host.Log(s))) return "a gesture is animating";
if (BusyCount > 0) return $"busy count {BusyCount}";
return "";
}
/// <summary>
/// One vitals pass with the idle (Top Off) lines. Returns what it did, for chat. Pump thread
/// (internal for the host tests).
/// </summary>
internal string RechargeOnceNow()
{
int hp = _vitals.HealthPct, st = _vitals.StaminaPct, mn = _vitals.ManaPct;
Func<bool>? saved = InCombatOverride;
InCombatOverride = static () => false; // the Top Off lines, monsters or not
bool acted;
try { acted = CheckVitals(); }
finally { InCombatOverride = saved; }
string vitals = $"health {hp}%, stamina {st}%, mana {mn}%";
_host.Log($"[RynthAi] Recharge (one pass, Top Off lines): {vitals}; acted={acted} heal={_isHealingSelf} stam={_isRechargingStamina} mana={_isRechargingMana} why='{_vitalWhy}'");
if (!acted)
{
bool under = hp < _settings.TopOffHP || st < _settings.TopOffStam || mn < _settings.TopOffMana;
return under
? $"nothing could recharge ({vitals}; Top Off {_settings.TopOffHP}/{_settings.TopOffStam}/{_settings.TopOffMana}%{(_vitalWhy.Length > 0 ? "; " + _vitalWhy : "")})."
: $"nothing to do ({vitals}, all at or over Top Off {_settings.TopOffHP}/{_settings.TopOffStam}/{_settings.TopOffMana}%).";
}
if (_isHealingSelf) return $"healing ({vitals}).";
if (_isRechargingStamina) return $"restoring stamina ({vitals}).";
if (_isRechargingMana) return $"restoring mana ({vitals}).";
return $"vitals step busy ({vitals}).";
}
}

View file

@ -0,0 +1,184 @@
// ============================================================================
// RynthSuite - Combat/BuffManager.RecoveryRetry.cs
// Fast retry of the recovery vitals (Heal Self, Stamina to Health, Revitalize,
// Stamina to Mana) after the server's "not enough mana" answer.
//
// ACE (origin/master, Creature_Magic.GetManaCost) rolls Mana Conversion on every
// cast attempt: a trained caster pays between the full cost and 1 mana. The roll
// and the check run before the windup (Player_Magic.CalculateManaUsage), so a
// refusal costs nothing: no mana, no busy period, no recoil, only UseDone 0x401.
// At low mana the cast goes through on a good roll, so trying again soon is the
// way to get it off. Before this, the refusal rested the spell's family (LowManaHealRestSec).
//
// Bounds (the refusal-spam crash class, see the "too busy" handler): the retry
// gap is never under RecoveryRetryMinMs, at most RecoveryRetryMaxPerSecond
// recovery casts go out in any second while an episode is open, and an episode
// stops after RecoveryRetryMaxRefusals mana refusals in a row (any recovery
// spell); the refused family then rests as before (a vital LowManaHealRestSec, 2 s).
// ============================================================================
using System;
using System.Collections.Generic;
using RynthCore.Plugin.RynthAi.LegacyUi;
namespace RynthCore.Plugin.RynthAi;
public partial class BuffManager
{
internal const int RecoveryRetryMinMs = 200;
internal const int RecoveryRetryMaxMs = 5000;
internal const int RecoveryRetryMaxPerSecond = 5;
internal const int RecoveryRetryMaxRefusals = 20;
// A refusal this long after the last one starts a new episode; an open episode with no refusal
// for this long ends. Above the slowest retry gap (the setting's 5000 ms maximum) with room for
// the pacing in between, so a slow setting never ends its own episode between two retries.
internal const double RecoveryEpisodeStaleMs = RecoveryRetryMaxMs + 2000;
// Stamina to Mana is attempted only above this stamina % (the CheckVitals and mana floor gates).
private const int RecoveryMinStaminaToConvert = 15;
private bool _recoveryOpen;
private DateTime _recoveryStartedAt;
private DateTime _recoveryLastRefusalAt;
private int _recoveryRefusals;
private readonly Dictionary<int, DateTime> _recoveryNextAt = new();
private readonly List<string> _recoveryNames = new();
// Recovery casts sent (any time), for the per-second ceiling.
private readonly Queue<DateTime> _recoveryAttempts = new();
// The base name of the pending vital ("Stamina to Mana Self"...), set by CastVital.
private string _pendingVitalBase = "";
/// <summary>Recovery casts held by the per-second ceiling (tests, status).</summary>
internal int RecoveryRateHolds { get; private set; }
/// <summary>The last episode summary line (tests, status).</summary>
internal string LastRecoverySummary { get; private set; } = "";
/// <summary>True while a fast-retry episode is open (tests).</summary>
internal bool RecoveryRetryOpen => _recoveryOpen;
internal static bool IsRecoveryVital(string baseName) =>
baseName is "Heal Self" or "Stamina to Health Self" or "Revitalize Self" or "Stamina to Mana Self";
private int RecoveryRetryMs => Math.Clamp(_settings.RecoveryRetryMs, RecoveryRetryMinMs, RecoveryRetryMaxMs);
/// <summary>
/// Why a fast retry can't help now, or "" when it can. Untrained Mana Conversion pays the full
/// cost every time (GetManaCost returns the base cost), so a retry would only be refused again;
/// trained, the least a cast can cost is 1 mana.
/// </summary>
private string RecoveryRetryBlocked(string baseName)
{
if (!IsSkillUsable(AcSkillType.ManaConversion)) return "Mana Conversion not trained (no cost roll)";
if (_vitals.MaxMana > 0 && _vitals.CurrentMana < 1) return "no mana at all";
if (baseName == "Stamina to Mana Self" && _vitals.StaminaPct <= RecoveryMinStaminaToConvert)
return $"stamina {_vitals.StaminaPct}% too low to convert";
if (baseName == "Stamina to Health Self" && _vitals.StaminaPct <= _settings.StaminaToHealthMinStamina)
return $"stamina {_vitals.StaminaPct}% too low to convert";
return "";
}
/// <summary>
/// "Not enough mana" for the pending cast. Returns true when it was a recovery vital that will be
/// retried soon (the caller then skips the family rest); false leaves the old handling.
/// </summary>
private bool OnRecoveryManaRefusal(SpellInfo? pending)
{
if (pending == null || _pendingSpellId != _pendingVitalSpellId || !IsRecoveryVital(_pendingVitalBase))
return false;
DateTime now = Now;
if (_recoveryOpen && (now - _recoveryLastRefusalAt).TotalMilliseconds > RecoveryEpisodeStaleMs)
EndRecoveryEpisode(now, "no refusal for a while", success: false, "");
if (!_recoveryOpen)
{
_recoveryOpen = true;
_recoveryStartedAt = now;
_recoveryRefusals = 0;
_recoveryNames.Clear();
}
_recoveryRefusals++;
_recoveryLastRefusalAt = now;
if (!_recoveryNames.Contains(pending.Name)) _recoveryNames.Add(pending.Name);
string blocked = RecoveryRetryBlocked(_pendingVitalBase);
if (blocked.Length > 0)
{
EndRecoveryEpisode(now, blocked, success: false, "");
return false;
}
if (_recoveryRefusals >= RecoveryRetryMaxRefusals)
{
EndRecoveryEpisode(now, $"{_recoveryRefusals} refusals in a row", success: false, "");
return false;
}
_recoveryNextAt[pending.Family] = now.AddMilliseconds(RecoveryRetryMs);
if (_recoveryRefusals == 1)
_host.Log($"[Vitals] {pending.Name}: not enough mana (mana {_vitals.CurrentMana}); retrying every {RecoveryRetryMs} ms for a Mana Conversion roll (at most {RecoveryRetryMaxPerSecond}/s, {RecoveryRetryMaxRefusals} refusals).");
return true;
}
/// <summary>A result line for <paramref name="family"/>: a retried cast went through.</summary>
private void OnRecoveryCastResult(int family, string name)
{
if (_recoveryOpen && _recoveryNextAt.ContainsKey(family))
EndRecoveryEpisode(Now, "", success: true, name);
}
private void EndRecoveryEpisode(DateTime now, string why, bool success, string name)
{
if (!_recoveryOpen) return;
_recoveryOpen = false;
_recoveryNextAt.Clear();
double ms = (now - _recoveryStartedAt).TotalMilliseconds;
string names = string.Join(", ", _recoveryNames);
LastRecoverySummary = success
? $"[Vitals] {name} went through after {_recoveryRefusals + 1} attempts ({_recoveryRefusals} refused for mana: {names}) in {ms:0} ms."
: $"[Vitals] stopped retrying {names} after {_recoveryRefusals} mana refusals in {ms:0} ms ({why}).";
_host.Log(LastRecoverySummary);
}
/// <summary>
/// Ends an episode with no refusal for RecoveryEpisodeStaleMs (the cast went through unseen, the
/// vital is no longer needed, or something else took over), so a stale one never keeps letting
/// casts past Spell Interval. Once per heartbeat.
/// </summary>
private void ExpireRecoveryEpisode()
{
if (_recoveryOpen && (Now - _recoveryLastRefusalAt).TotalMilliseconds > RecoveryEpisodeStaleMs)
EndRecoveryEpisode(Now, $"no refusal for {RecoveryEpisodeStaleMs / 1000:0} s", success: false, "");
}
/// <summary>
/// The cast interval gate lets a due recovery retry through: the retry gap (RecoveryRetryMs)
/// replaces Spell Interval for it, and the per-second ceiling still applies in CastVital.
/// </summary>
private bool RecoveryRetryDue()
{
if (!_recoveryOpen) return false;
DateTime now = Now;
foreach (var at in _recoveryNextAt.Values)
if (now >= at) return true;
return false;
}
/// <summary>CastVital's gate for a recovery vital while an episode is open: "" to cast, else why it waits.</summary>
private string RecoveryRetryHolds(int family)
{
if (!_recoveryOpen) return "";
DateTime now = Now;
if (_recoveryNextAt.TryGetValue(family, out DateTime next) && now < next)
return $"retrying after a mana refusal in {(next - now).TotalMilliseconds:0} ms";
while (_recoveryAttempts.Count > 0 && (now - _recoveryAttempts.Peek()).TotalMilliseconds >= 1000)
_recoveryAttempts.Dequeue();
if (_recoveryAttempts.Count >= RecoveryRetryMaxPerSecond)
{
RecoveryRateHolds++;
return $"{RecoveryRetryMaxPerSecond} recovery casts in the last second";
}
return "";
}
private void NoteRecoveryAttempt()
{
DateTime now = Now;
while (_recoveryAttempts.Count > 0 && (now - _recoveryAttempts.Peek()).TotalMilliseconds >= 1000)
_recoveryAttempts.Dequeue();
_recoveryAttempts.Enqueue(now);
}
}

View file

@ -0,0 +1,133 @@
using System;
using RynthCore.PluginSdk;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthAi;
// The heal seam of the script-provided combat hook (RynthAi.Combat, CombatHookInterface.cs):
// CheckVitals asks the script for the heal spell (and its target: the player, or a monster for a
// drain) before kits. The cast itself goes through CastVital, the same steps as Heal Self.
public partial class BuffManager
{
/// <summary>
/// True when the hook handled this vitals check: waiting for the answer, or the answer was
/// cast (or its wand swap is in flight). False = the native order (kit, Heal Self, potion).
/// </summary>
private bool TryScriptHeal(int healLine, bool inCombat)
{
// AC just said "You're too busy!": the same pacing as a Heal Self (AttemptVitalCast).
if (DateTime.Now < _busyBackoffUntil && (DateTime.Now - _lastCastAttempt).TotalMilliseconds < BusyHealRetryMs)
{
_vitalWhy = $"AC too busy, waiting {(_busyBackoffUntil - DateTime.Now).TotalMilliseconds:0} ms";
_healWaitKind = "too-busy backoff";
return true;
}
var slot = CombatHook.Heal;
// The request names RynthAi's fight target when it opened (informational: the monster with
// live health data, e.g. for a drain). A fight target change does not re-ask (the heal keeps
// its deadline); the answer's target is checked as things stand when it comes. The
// answer's target 0 still means the player.
var cm = _combatManager;
uint fight = cm == null ? 0u : unchecked((uint)cm.activeTargetId);
var outcome = CombatHook.Step(slot, fight, () => BuildHealRequest(healLine, inCombat), s => _host.Log(s),
out uint spell, out uint target, out _);
switch (outcome)
{
case CombatHook.Outcome.Native:
return false;
case CombatHook.Outcome.Wait:
_vitalWhy = $"waiting for '{CombatHook.Owner}' to choose the heal";
_healWaitKind = "script choosing the heal";
return true;
}
uint player = (uint)_host.GetPlayerId();
if (target == 0) target = player;
string? why = ScriptHealProblem(spell, target, player);
if (why != null)
{
CombatHook.Reject(slot, why, s => _host.Log(s));
return false;
}
string name = SpellTableStub.GetById((int)spell)?.Name ?? $"spell {spell}";
bool handled = CastVital((int)spell, target, LabelHealing, name + " (script)", out bool sent);
if (!handled)
{
CombatHook.Reject(slot, _vitalWhy.Length > 0 ? _vitalWhy : "it couldn't be cast", s => _host.Log(s));
return false;
}
// A script-chosen heal takes no early nudge (HeldNudgeUrgent): its result can come later
// than RynthAi's own heals' (Vitality Siphon: 2.42-2.75 s after the incantation, 2026-10-10
// log), or never (a resisted or dead target), and an early nudge steps the character.
if (sent && _cast.Current is { } sentCast && sentCast.SpellId == (int)spell) sentCast.Script = true;
if (sent) ActionPacer.MarkScriptCast((int)spell); // the stuck-cast breaker gives it the same room
// Handled: cast, or a swap step to Magic mode is in flight (the next check asks again).
CombatHook.Cast(slot, sent ? spell : 0, sent ? target : 0, sent ? ActionPacer.LastCastSeqAtSend : -1);
if (sent) _host.Log($"[RynthAi] Vitals: script heal id={spell} '{name}' at 0x{target:X8} (owner '{CombatHook.Owner}').");
return true;
}
/// <summary>Why the script's heal can't be cast, or null when it can.</summary>
private string? ScriptHealProblem(uint spell, uint target, uint player)
{
if (!_spellManager.IsKnownSpellId((int)spell)) return $"spell {spell} isn't known";
// The refusal memory RynthAi's own heal honours (AttemptVitalCast): a level the server
// said there are no components for.
if (LevelLacksComponents((int)spell)) return $"spell {spell} has no components (refused by the server; RynthAi uses a lower level)";
if (target == player) return null;
// A heal cast at anything but the player has to take health from the target and give it
// to the caster (a vital transfer: Drain Health, Vitality Siphon...). Any other spell at a
// monster heals or buffs the monster.
if (!IsDrainToCaster((int)spell)) return $"spell {spell} at a monster is not a drain (a heal may target a monster only with a vital transfer to the caster)";
var cm = _combatManager;
// Monster rule Priority 0 = never attacked: a drain at one is refused too, even when it is
// still the fight target (its rule changed before Think dropped it) or still scanned.
if (cm != null && cm.IsIgnored(unchecked((int)target))) return "the target is ignored (monster rule Priority 0)";
bool listed = cm != null && unchecked((uint)cm.activeTargetId) == target;
if (!listed && cm != null)
foreach (var t in cm.ScannedTargets)
if (unchecked((uint)t.Id) == target) { listed = true; break; }
if (!listed) return "the target is not the player, the fight target or a scanned monster";
if (_host.HasObjectIsAttackable && !_host.ObjectIsAttackable(target)) return "the target is not attackable";
return null;
}
/// <summary>
/// True for a vital transfer from the target to the caster (Drain Health Other, Vitality
/// Siphon, Soul Shroud, Drain Mana/Stamina...), read from the spell catalog: a
/// "...Transfertocaster" family, cast on Other, described as taking the target's vital and
/// giving it to the caster. A spell the catalog doesn't have (a custom server's) counts by its
/// name: "Drain " or "Siphon".
/// </summary>
internal static bool IsDrainToCaster(int spellId)
{
SpellCatalog.EnsureLoaded();
var e = SpellCatalog.Get(spellId);
if (e != null)
return e.FamilyName.EndsWith("Transfertocaster", StringComparison.OrdinalIgnoreCase)
&& e.Target.Equals("Other", StringComparison.OrdinalIgnoreCase)
&& e.Description.Contains("the target's", StringComparison.OrdinalIgnoreCase)
&& e.Description.Contains("to the caster", StringComparison.OrdinalIgnoreCase);
string name = SpellTableStub.GetById(spellId)?.Name ?? "";
return name.Contains("Drain ", StringComparison.OrdinalIgnoreCase) || name.Contains("Siphon", StringComparison.OrdinalIgnoreCase);
}
private CombatRequestV1 BuildHealRequest(int healLine, bool inCombat)
{
bool known = _vitals.MaxHealth > 0;
var cm = _combatManager;
float fightHealth = cm?.FightTargetHealthRatio ?? -1f;
return new CombatRequestV1
{
TargetHealth = fightHealth,
HealthPct = known ? _vitals.HealthPct : -1,
StaminaPct = _vitals.MaxStamina > 0 ? _vitals.StaminaPct : -1,
ManaPct = _vitals.MaxMana > 0 ? _vitals.ManaPct : -1,
HealLine = healLine,
InCombat = inCombat ? 1 : 0,
CombatMode = CurrentCombatMode,
};
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,194 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Text.Json;
using RynthCore.Install;
namespace RynthCore.Plugin.RynthAi;
/// <summary>
/// A buff profile: the spells buffing keeps up, in cast order. Built in the Spells window
/// (/ra spells) and chosen under Loaded Files (Buffs). Without one, buffing uses its
/// built-in list.
/// </summary>
public sealed class BuffProfile
{
public int Schema = BuffProfileStore.CurrentSchema;
public string Name = "";
public string Notes = "";
public List<BuffProfileEntry> Entries = new();
}
/// <summary>One spell line in a <see cref="BuffProfile"/>.</summary>
public sealed class BuffProfileEntry
{
/// <summary>The spell picked in the Spells window (shown in the profile list).</summary>
public int SpellId;
public string Name = "";
/// <summary>
/// Base name buffing resolves to the best tier the character knows ("Strength Self");
/// see <see cref="SpellCatalog.BuffKeyFor"/>.
/// </summary>
public string Key = "";
/// <summary>ACE spell family: the fallback when the base name has no tier ladder.</summary>
public int FamilyId;
public string School = "";
public string Target = "";
public int Level;
public bool Enabled = true;
}
/// <summary>
/// Buff profile files: <c>&lt;SuiteDir&gt;\RynthAi\BuffProfiles\&lt;name&gt;.json</c>, shared by
/// every character like the Nav, Loot and Meta folders.
/// </summary>
internal static class BuffProfileStore
{
public const int CurrentSchema = 1;
public const string FileExtension = ".json";
/// <summary>Tests point the folder at a temp directory.</summary>
internal static string? FolderOverride;
public static string Folder => FolderOverride ?? Path.Combine(RynthInstallPaths.RynthAiDir, "BuffProfiles");
/// <summary>Full path for a profile name (sanitised for Windows file names).</summary>
public static string PathFor(string profileName) =>
Path.Combine(Folder, SanitizeFileName(profileName) + FileExtension);
/// <summary>Profile file names (with extension) in the folder, sorted.</summary>
public static List<string> ListFileNames()
{
var list = new List<string>();
try
{
if (!Directory.Exists(Folder)) return list;
foreach (string f in Directory.GetFiles(Folder, "*" + FileExtension))
list.Add(Path.GetFileName(f));
list.Sort(StringComparer.OrdinalIgnoreCase);
}
catch { /* folder unreadable: no profiles */ }
return list;
}
public static bool TryLoad(string path, out BuffProfile profile, out string error)
{
profile = new BuffProfile();
error = "";
try
{
if (string.IsNullOrWhiteSpace(path) || !File.Exists(path)) { error = "file not found"; return false; }
var p = JsonSerializer.Deserialize(File.ReadAllText(path), RynthAiJsonContext.Default.BuffProfile);
if (p == null) { error = "empty file"; return false; }
if (p.Schema > CurrentSchema) { error = $"made by a newer RynthAi (schema {p.Schema})"; return false; }
Normalize(p, Path.GetFileNameWithoutExtension(path));
profile = p;
return true;
}
catch (Exception ex)
{
error = ex.Message;
return false;
}
}
/// <summary>Writes the profile (temp file + move, so a crash never leaves half a file).</summary>
public static void Save(BuffProfile profile, string path)
{
Normalize(profile, Path.GetFileNameWithoutExtension(path));
profile.Schema = CurrentSchema;
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
string tmp = path + ".tmp";
File.WriteAllText(tmp, JsonSerializer.Serialize(profile, RynthAiJsonContext.Default.BuffProfile));
File.Move(tmp, path, overwrite: true);
}
public static bool Delete(string path)
{
try
{
if (!File.Exists(path)) return false;
File.Delete(path);
return true;
}
catch { return false; }
}
/// <summary>An entry for a catalog spell, with its buffing key worked out.</summary>
public static BuffProfileEntry EntryFor(SpellCatalogEntry e) => new()
{
SpellId = e.Id,
Name = e.Name,
Key = SpellCatalog.BuffKeyFor(e),
FamilyId = e.FamilyId,
School = e.School,
Target = e.Target,
Level = e.Level,
Enabled = true,
};
/// <summary>True when an entry with the same buffing key is already in the profile.</summary>
public static bool ContainsKey(BuffProfile p, string key)
{
foreach (var e in p.Entries)
if (e.Key.Equals(key, StringComparison.OrdinalIgnoreCase)) return true;
return false;
}
/// <summary>
/// Catalog spell for one of buffing's built-in base names ("Strength Self", "Blade Bane",
/// "Blood Drinker Self"), used to start a profile from the built-in list. Null when the
/// catalog has no tier ladder for it.
/// </summary>
public static SpellCatalogEntry? CatalogSpellForBaseName(string baseName)
{
string[] candidates =
{
baseName + " I", "Aura of " + baseName + " I", baseName + " II", "Aura of " + baseName + " II",
baseName, "Incantation of " + baseName,
};
foreach (string c in candidates)
{
var e = SpellCatalog.GetByName(c);
if (e != null) return e;
}
return null;
}
/// <summary>Repairs nulls, blank keys and the name after loading or before saving.</summary>
public static void Normalize(BuffProfile p, string fallbackName)
{
p.Name = string.IsNullOrWhiteSpace(p.Name) ? fallbackName : p.Name.Trim();
p.Notes ??= "";
p.Entries ??= new List<BuffProfileEntry>();
p.Entries.RemoveAll(e => e == null || (e.SpellId == 0 && string.IsNullOrWhiteSpace(e.Key)));
foreach (var e in p.Entries)
{
e.Name ??= "";
e.School ??= "";
e.Target ??= "";
e.Key ??= "";
// Hand-edited files may hold only a spell id: fill the rest from the catalog.
var c = e.SpellId != 0 ? SpellCatalog.Get(e.SpellId) : null;
if (c != null)
{
if (e.Name.Length == 0) e.Name = c.Name;
if (e.Key.Length == 0) e.Key = SpellCatalog.BuffKeyFor(c);
if (e.FamilyId == 0) e.FamilyId = c.FamilyId;
if (e.School.Length == 0) e.School = c.School;
if (e.Target.Length == 0) e.Target = c.Target;
if (e.Level == 0) e.Level = c.Level;
}
if (e.Key.Length == 0) e.Key = SpellCatalog.StripTier(e.Name);
}
}
/// <summary>Strips characters Windows forbids in file names; "Default" when nothing is left.</summary>
public static string SanitizeFileName(string name)
{
string t = (name ?? "").Trim();
foreach (char c in Path.GetInvalidFileNameChars()) t = t.Replace(c, '_');
if (t.Length > 80) t = t.Substring(0, 80);
return t.Length == 0 ? "Default" : t;
}
}

View file

@ -38,6 +38,9 @@ internal sealed class CastTracker
public bool Done; // its result line, or UseDone(0) after its incantation
public bool Nudged; // the one movement nudge for this held cast has gone out
public bool StuckLogged;
// The script combat hook chose this cast (a heal): no early nudge, HeldAfterIncantMs only.
// A Vitality Siphon's result can come 2.75 s after its incantation (2026-10-10 log).
public bool Script;
public bool HasIncantation => IncantAt != DateTime.MinValue;
}

View file

@ -0,0 +1,291 @@
using System;
using RynthCore.PluginSdk;
using RynthCore.Plugin.RynthAi.Combat;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthAi;
// The attack seam of the script-provided combat hook (RynthAi.Combat, CombatHookInterface.cs):
// with a script holding the attack kind, AttackWithMagic asks it for the spell after its debuffs
// and before its own shape choice. RynthAi keeps everything around the cast: the scan, the
// target lock, the stance, the cadence and busy gates, and the cast bookkeeping. The script only
// names the spell (and optionally another scanned monster, or the player).
public partial class CombatManager
{
// True on a tick where AttackWithMagic sent nothing because it is waiting on the script's
// answer: Think then ends the tick without stamping lastAttackCmd (like the wall hold).
private bool _scriptHeld;
/// <summary>The player's vitals, for the hook's request (set by the plugin; null in tests that don't need it).</summary>
internal PlayerVitalsCache? Vitals { get; set; }
/// <summary>The fight target's last known health ratio (0-1), or -1 when unknown or no target.</summary>
internal float FightTargetHealthRatio => activeTargetId == 0 ? -1f : _worldFilter.GetHealthRatio(activeTargetId);
/// <summary>Host tests: true after a tick that held for the script's answer.</summary>
internal bool ScriptHeld => _scriptHeld;
/// <summary>
/// True when the hook handled this attack cycle: held for the answer, or cast the script's
/// spell. False = RynthAi chooses as usual (no hook, a decline, a rejected answer, a timeout).
/// </summary>
private bool TryScriptAttack(WorldObject target, string element)
{
if (!CombatHook.IsActive(RynthAiCombat.KindAttack)) return false; // no hook: no per-tick lambdas
var slot = CombatHook.Attack;
uint forTarget = unchecked((uint)activeTargetId);
var outcome = CombatHook.Step(slot, forTarget, () => BuildAttackRequest(target), s => _host.Log(s),
out uint spell, out uint castTarget, out uint flags);
switch (outcome)
{
case CombatHook.Outcome.Native:
return false;
case CombatHook.Outcome.Wait:
_scriptHeld = true;
LastCombatSkipReason = "script-wait"; // D4 record-only
return true;
}
if (castTarget == 0) castTarget = forTarget;
string? why = ScriptAttackProblem(spell, castTarget);
if (why != null)
{
CombatHook.Reject(slot, why, s => _host.Log(s));
return false;
}
// A spell that costs more than max mana can never be paid, so the mana hold below would
// never lift: rejected, and RynthAi chooses its own spell this same tick.
bool affordable = true;
try { affordable = ManaCanEverAfford?.Invoke((int)spell) ?? true; } catch { affordable = true; }
if (!affordable)
{
CombatHook.Reject(slot, "costs more than max mana", s => _host.Log(s));
return false;
}
// RynthAi's mana reserve holds the script's spell as it holds its own (ManaHoldsCast: mana
// under the spell's cost, or under the reserve kept for Stamina to Mana): nothing is sent,
// Think ends the tick on _manaCastHeld, and the answer is kept for the next tick. It is not
// a rejection, so RynthAi does not cast a spell of its own choosing instead. Once the
// request is past its deadline + StaleGraceMs, Step drops the answer and asks again.
if (ManaHoldsCast((int)spell)) return true;
if (!IssueScriptCast((int)spell, castTarget, flags, element))
{
CombatHook.Reject(slot, "the client refused the cast", s => _host.Log(s));
return false;
}
CombatHook.Cast(slot, spell, castTarget, ActionPacer.LastCastSeqAtSend);
return true;
}
/// <summary>Why the script's answer can't be cast, or null when it can.</summary>
private string? ScriptAttackProblem(uint spell, uint castTarget)
{
if (_spellManager == null || !_spellManager.IsKnownSpellId((int)spell)) return $"spell {spell} isn't known";
// A script spell the server refused outright (no components): parked like a vital level.
if (_scriptParkedUntil.TryGetValue((int)spell, out DateTime parked) && DateTime.Now < parked)
return $"spell {spell} was refused by the server, parked for {(parked - DateTime.Now).TotalSeconds:0} s more";
uint player = _playerId != 0 ? _playerId : _host.GetPlayerId();
if (castTarget == player) return null;
// Monster rule Priority 0 = IGNORE: not a target for a script either, even one attacking us.
// Checked before the fight-target match: a fight target whose rule changed to 0 is still
// the active target until Think drops it.
if (IsIgnored((int)castTarget)) return "the target is ignored (monster rule Priority 0)";
bool listed = castTarget == unchecked((uint)activeTargetId);
for (int i = 0; !listed && i < _scannedTargets.Count; i++)
if (unchecked((uint)_scannedTargets[i].Id) == castTarget) listed = true;
if (!listed) return "the target is not the fight target, a scanned monster or the player";
// The same veto as RynthAi's own casts: never offensive magic at something AC says isn't attackable.
if (_host.HasObjectIsAttackable && !_host.ObjectIsAttackable(castTarget)) return "the target is not attackable";
return null;
}
private CombatRequestV1 BuildAttackRequest(WorldObject target)
{
var v = Vitals;
bool vitalsKnown = v != null && v.MaxHealth > 0;
return new CombatRequestV1
{
TargetHealth = _worldFilter.GetHealthRatio(activeTargetId),
HealthPct = vitalsKnown ? v!.HealthPct : -1,
StaminaPct = vitalsKnown && v!.MaxStamina > 0 ? v.StaminaPct : -1,
ManaPct = vitalsKnown && v!.MaxMana > 0 ? v.ManaPct : -1,
HealLine = 0,
InCombat = 1,
CombatMode = CurrentCombatMode,
};
}
/// <summary>
/// Sends the script's spell with RynthAi's own cast bookkeeping: the cadence guard
/// (MarkCombatCastIssued), the attack interval and the area flag. The pending-offensive
/// judgement (blacklist on no damage) is armed only for a single-target cast at the fight
/// target without NOJUDGE. A damaging cast at the fight target (not NOJUDGE) is tagged for
/// the Damage tab like RynthAi's own: wielded wand, element and level from the spell, the
/// fight's cast count and the last-fight snapshot; a single-target one also runs the
/// kill-shot prediction (EvaluateKillShot), as RynthAi's own cast does.
/// </summary>
private bool IssueScriptCast(int spellId, uint castTarget, uint flags, string fallbackElement)
{
bool area = (flags & RynthAiCombat.FlagArea) != 0;
bool noJudge = (flags & RynthAiCombat.FlagNoJudge) != 0;
string name = SpellTableStub.GetById(spellId)?.Name ?? $"spell {spellId}";
bool ok;
try { ok = _host.CastSpellFor(castTarget, spellId, "Combat", name + " (script)"); }
catch { ok = false; }
if (!ok) return false;
ActionPacer.MarkScriptCast(spellId);
MarkCombatCastIssued();
StartCastChatTrace(spellId, unchecked((int)castTarget)); // the server's answers, logged as for RynthAi's own casts
SessionAttackCasts++;
CastsSinceLastKill++;
_lastSpellCast = DateTime.Now;
_scriptCastSpellId = spellId;
_scriptCastAt = DateTime.Now;
_scriptCastSent = ActionPacer.CastsSent; // includes this cast: any later send changes it
bool atFight = castTarget == unchecked((uint)activeTargetId);
bool judged = atFight && !area && !noJudge;
_lastCastWasRing = !judged; // anything else gets no per-target judgement
_wallFaceAt = DateTime.MinValue;
if (judged)
{
// What the NO DAMAGE report names as the last cast (ReportNoDamageCasts).
_lastOffensiveCastLine = $"script id={spellId} '{name}' target=0x{castTarget:X8}";
_pendingOffensiveSpellId = spellId;
_pendingOffensiveCastAt = DateTime.Now;
_pendingOffensiveTargetId = activeTargetId;
NoteOffensiveSeq();
}
// As the native block: a throw here must not fail the cast that already went out (the
// slot would stay Decided and the same answer be cast again).
// A single-target damaging cast at the fight target also takes part in RynthAi's kill-shot
// swap (Think arms it, the deferred swap moves on while the projectile flies), with the
// weapon, element and tier just tagged. Area, nojudge and off-target casts never do.
_predictKillSwap = false;
if (atFight && !noJudge)
{
try
{
TagScriptCast(spellId, area, fallbackElement);
if (!area) EvaluateKillShot(_lastCastWeaponId, _lastCastElement, _lastCastTier, isRing: false);
}
catch { }
}
LastCombatSkipReason = "script-cast"; // D4 record-only
string tags = (area ? " (area)" : "") + (noJudge ? " (nojudge)" : "");
_host.Log($"[CombatCast] script id={spellId} '{name}' at 0x{castTarget:X8}{tags} " +
$"fight=0x{activeTargetId:X8} owner='{CombatHook.Owner}'");
return true;
}
/// <summary>
/// The damage attribution RynthAi's own cast does (AttackWithMagic), for a script's cast at
/// the fight target: the weapon, element and tier the pushed damage is filed under, the
/// Damage tab's latest tier, the casts-to-kill count and the last-fight snapshot.
/// </summary>
private void TagScriptCast(int spellId, bool area, string fallbackElement)
{
int castWand = InHandWeaponId();
if (castWand == 0 || !IsWandObject(_worldFilter[castWand] ?? new WorldObject(0, ""))) castWand = FindWandInItems();
_lastCastWeaponId = unchecked((uint)castWand);
// No element in the spell (a Life drain, say) on a caster with no War or Void: the plan's
// element (a weapon-weakness pick like "Slash") would be wrong, so it is filed under
// "Physical", the key RynthAi's own damage path already uses for vital drains.
_lastCastElement = ScriptSpellElement(spellId) ?? (AttackMagicTrained ? fallbackElement : "Physical");
int castLevel = SpellTableStub.GetById(spellId)?.Level ?? 0;
if (castLevel <= 0 && SpellDatabase.TryGetCategoryAndPower(spellId, out _, out int castPower))
castLevel = SpellDatabase.LevelFromPower(castPower);
if (castLevel <= 0)
castLevel = Math.Max(_spellManager?.GetHighestSpellTier(AcSkillType.WarMagic) ?? 0,
_spellManager?.GetHighestSpellTier(AcSkillType.VoidMagic) ?? 0);
_lastCastTier = area ? -castLevel : castLevel; // area casts filed with the rings (negative)
if (_fightTargetWcid != 0) _damageStore?.NoteCast(_fightTargetWcid, _lastCastTier, _fightTargetName);
_fightCastCount++;
if (_fightTargetWcid != 0)
{
_lastFightWcid = _fightTargetWcid;
_lastFightName = _worldFilter[activeTargetId]?.Name ?? _fightTargetName;
_lastFightWeaponId = _lastCastWeaponId;
_lastFightElement = _lastCastElement;
_lastFightTier = _lastCastTier;
_lastFightCount = _fightCastCount;
StampRecentFight();
}
}
/// <summary>
/// The element of a war/void attack spell, from RynthAi's own shape tables (base name, tier-7
/// lore names, ring lore names, wall categories), else from its name's words; null when
/// none of those says.
/// </summary>
internal static string? ScriptSpellElement(int spellId)
{
string? name = SpellTableStub.GetById(spellId)?.Name;
if (string.IsNullOrEmpty(name)) return null;
string n = name.Trim();
if (n.StartsWith("Incantation of ", StringComparison.OrdinalIgnoreCase)) n = n.Substring(15).Trim();
int sp = n.LastIndexOf(' ');
if (sp > 0 && IsRoman(n.Substring(sp + 1))) n = n.Substring(0, sp);
// Blade and Slash share their spells: answer Slash (the Damage tab's element name).
foreach (var kv in SpellShapes)
if (!kv.Key.Equals("Blade", StringComparison.OrdinalIgnoreCase)
&& Array.Exists(kv.Value, b => b.Equals(n, StringComparison.OrdinalIgnoreCase)))
return kv.Key;
foreach (var table in new[] { WarTier7Lore, RingLoreNames })
foreach (var kv in table)
if (!kv.Key.Equals("Blade", StringComparison.OrdinalIgnoreCase)
&& Array.Exists(kv.Value, b => b.Equals(name.Trim(), StringComparison.OrdinalIgnoreCase)))
return kv.Key;
if (SpellDatabase.TryGetCategoryAndPower(spellId, out int category, out _))
foreach (var kv in WallCategories)
if (kv.Value == category && !kv.Key.Equals("Blade", StringComparison.OrdinalIgnoreCase)) return kv.Key;
string byWords = PetChoice.ElementFromName(name);
return byWords.Length > 0 ? byWords : null;
static bool IsRoman(string s)
{
if (s.Length == 0) return false;
foreach (char c in s) if (c != 'I' && c != 'V' && c != 'X') return false;
return true;
}
}
// -- Refusal memory for script casts --
// The script's last cast, while it is still the last cast this plugin sent (ActionPacer counts
// every send: combat, buffs and heals, nav, commands, meta): a hard refusal arriving soon after
// it is the script spell's, and parks that spell. Forgotten once any other cast goes out, the
// spell's own success line arrives, or the window passes.
private int _scriptCastSpellId;
private DateTime _scriptCastAt = DateTime.MinValue;
private long _scriptCastSent;
private readonly System.Collections.Generic.Dictionary<int, DateTime> _scriptParkedUntil = new();
/// <summary>How long a script spell the server refused outright is rejected (as BuffManager parks a vital level).</summary>
internal const double ScriptParkSec = 600.0;
/// <summary>A refusal later than this after the script's cast is not attributed to it.</summary>
internal const double ScriptRefusalWindowMs = 2_000.0;
/// <summary>Host tests: true while <paramref name="spellId"/> is parked after a refusal.</summary>
internal bool ScriptSpellParked(int spellId) => _scriptParkedUntil.TryGetValue(spellId, out DateTime u) && DateTime.Now < u;
/// <summary>A chat line: park the script's last spell on a hard refusal (missing components, unknown spell).</summary>
private void NoteScriptCastRefusal(string text)
{
if (_scriptCastSpellId == 0) return;
if (ActionPacer.CastsSent != _scriptCastSent
|| (DateTime.Now - _scriptCastAt).TotalMilliseconds > ScriptRefusalWindowMs) { _scriptCastSpellId = 0; return; }
string lo = text.ToLowerInvariant();
string? own = SpellTableStub.GetById(_scriptCastSpellId)?.Name;
if (own != null && lo.Contains("ou cast " + own.ToLowerInvariant())) { _scriptCastSpellId = 0; return; } // it landed
if (!(lo.Contains("missing some required") || lo.Contains("you do not have the")
|| lo.Contains("have all the components for this spell"))) return;
int spell = _scriptCastSpellId;
_scriptCastSpellId = 0;
_scriptParkedUntil[spell] = DateTime.Now.AddSeconds(ScriptParkSec);
_host.Log($"[CombatCast] script spell id={spell} '{SpellTableStub.GetById(spell)?.Name}' refused: '{text.Trim()}'. " +
$"Rejected for {ScriptParkSec / 60:0} min (RynthAi chooses instead while the script asks for it).");
}
}

View file

@ -0,0 +1,116 @@
// ============================================================================
// RynthSuite - Combat/CombatManager.TargetLock.cs
// Target lock (VTank's "Target lock" hotkey, /ra targetlock): the macro attacks
// the monster the player selected, ahead of the Targeting setting, the rule
// Priority tiers (Priority 0 "ignore" included) and the never-attack name list.
//
// The selected monster must be attackable and alive. It joins the scan like the
// engaged target (out to the disengage distance); LOS and the failure blacklist
// still apply, so a monster behind a wall waits until it is in sight. While it
// isn't in the scan the normal selection runs. The lock ends when it dies or
// turns into a corpse, gets blacklisted (unreachable), is out of the scan for
// ForcedTargetLostMs, or the player clears it (/ra targetlock off, or the same
// monster again).
// ============================================================================
using System;
using System.Threading;
namespace RynthCore.Plugin.RynthAi;
public partial class CombatManager
{
/// <summary>Out of the scan this long (never in reach, or gone): the lock ends.</summary>
internal const double ForcedTargetLostMs = 30_000;
private int _forcedTargetId;
// Pump-thread state: when the current forced target was first and last seen.
private int _forcedSeenFor;
private DateTime _forcedSince = DateTime.MinValue;
private DateTime _forcedLastInScan = DateTime.MinValue;
/// <summary>The monster the player locked combat onto (0 = none). Any thread.</summary>
public int ForcedTargetId => Volatile.Read(ref _forcedTargetId);
/// <summary>Why <paramref name="id"/> can't be locked onto, or null when it can.</summary>
internal string? ForcedTargetRefusal(int id)
{
if (id == 0) return "nothing is selected";
if (unchecked((uint)id) == _playerId) return "that's you";
var wo = _worldFilter[id];
if (wo == null) return "it isn't known yet (try again in a moment)";
if ((int)wo.ObjectClass != (int)AcObjectClass.Monster || IsSpellProjectileName(wo.Name)) return $"{wo.Name} isn't a monster";
if (_host.HasObjectIsAttackable && !_host.ObjectIsAttackable(unchecked((uint)id))) return $"{wo.Name} can't be attacked";
if (_worldFilter.GetHealthRatio(id) == 0f || _recentlyKilled.ContainsKey(id)) return $"{wo.Name} is dead";
return null;
}
/// <summary>Locks combat onto <paramref name="id"/> (checked with <see cref="ForcedTargetRefusal"/> first).</summary>
internal void SetForcedTarget(int id) => Volatile.Write(ref _forcedTargetId, id);
/// <summary>Ends the target lock (the monster stays the fight target until normal selection moves on).</summary>
internal void ClearForcedTarget() => Volatile.Write(ref _forcedTargetId, 0);
/// <summary>
/// HandleCombatTrigger, before the normal selection: true when the forced target holds the
/// tick (locked now, or kept while it blinks out of the scan).
/// </summary>
private bool TryLockForcedTarget()
{
int fid = ForcedTargetId;
if (fid == 0) return false;
DateTime now = TargetClock();
if (_forcedSeenFor != fid)
{
_forcedSeenFor = fid;
_forcedSince = now;
_forcedLastInScan = DateTime.MinValue;
}
string? end = ForcedTargetEnded(fid, now);
if (end != null)
{
Interlocked.CompareExchange(ref _forcedTargetId, 0, fid);
string name = _worldFilter[fid]?.Name ?? $"0x{(uint)fid:X8}";
_host.Log($"[CombatTarget] target lock on 0x{(uint)fid:X8} '{name}' ended: {end}");
_host.WriteToChat($"[RynthAi] Target lock on {name} ended: {end}.", 1);
return false;
}
foreach (var c in _scannedTargets)
{
if (c.Id != fid) continue;
_forcedLastInScan = now;
int priority = PriorityOf(fid);
if (_lockedTargetId == fid)
{
activeTargetId = fid;
_lockedPriority = priority;
_lockedLastSeen = c;
_lockedLastSeenInScan = now;
return true;
}
LockTarget(c, priority, $"target lock: picked by the player, {DescribeTargetPos(fid)}",
_lockedTargetId != 0 ? "target lock" : null);
return true;
}
// Locked and briefly out of the scan: kept within the scan grace (the normal path would
// drop a Priority 0 monster at once).
return _lockedTargetId == fid && _lockedLastSeenInScan != DateTime.MinValue
&& (now - _lockedLastSeenInScan).TotalMilliseconds <= TARGET_SCAN_GRACE_MS;
}
private string? ForcedTargetEnded(int fid, DateTime now)
{
if (_recentlyKilled.ContainsKey(fid)) return "killed";
var wo = _worldFilter[fid];
if (wo != null && (int)wo.ObjectClass != (int)AcObjectClass.Monster) return "it died";
if (wo != null && _worldFilter.GetHealthRatio(fid) == 0f) return "it died";
if (_blacklistManager.IsBlacklisted(fid)) return "it can't be reached (blacklisted)";
DateTime seen = _forcedLastInScan != DateTime.MinValue ? _forcedLastInScan : _forcedSince;
if ((now - seen).TotalMilliseconds > ForcedTargetLostMs)
return _forcedLastInScan == DateTime.MinValue ? "never in reach (out of range or out of sight)" : "out of reach";
return null;
}
}

View file

@ -65,6 +65,7 @@ public partial class CombatManager : IDisposable
// equip path would only re-send ChangeCombatMode forever (it never re-equips a
// "wielded" wand) — a hours-long wedge with NO m_cBusy pin so no watchdog fires.
private DateTime _stanceStuckSince = DateTime.MinValue;
private long _stanceStuckStartMs; // ActionPacer.NowMs when the clock started (a later engine refusal restarts it)
private DateTime _lastStanceRecoverAt = DateTime.MinValue;
private const double StanceStuckRecoverMs = 8000;
// Re-equip attempts spent in the CURRENT deadlock episode. ⚠ UseObject on an
@ -296,6 +297,11 @@ public partial class CombatManager : IDisposable
/// Stamina to Mana), or null to cast. Null hook = never hold (2026-10-11).
/// </summary>
public Func<int, string?>? ManaReserveHold { get; set; }
/// <summary>
/// BuffManager.CanEverAfford, for the script hook: false when a spell costs more than max mana,
/// so ManaReserveHold would hold it forever. Null hook = always affordable.
/// </summary>
public Func<int, bool>? ManaCanEverAfford { get; set; }
private bool _manaCastHeld; // AttackWithMagic held its cast for mana this tick
private bool _manaHoldLogged;
@ -417,6 +423,36 @@ public partial class CombatManager : IDisposable
private string _lastSwingEvidenceKind = "none";
private readonly CombatStallWatchdog _stallWatch = new();
// ── Early stall step and stale objects (Drakkon 2026-10-12, Olthoi in 0x6146) ────────────
// The flight recorder showed the stall: the server answered a MeleeAttack with a MoveToObject
// to the target 2 m away, the character took a step and stopped, and the server waited for it
// to arrive; every further attack was dropped ("already in melee loop") until the watchdog's
// CancelAttack 6 s later, after which the server turned us and swung at once. Three such
// stalls cost 7-9 s each and one good target got blacklisted a second after the cancel. Now
// step 1 goes out after QuietStallMs when the stall is plain to see: attacks sent, no swing
// playing, the character standing still (see SampleMeleeQuiet).
// From 21:00 the same client fought four "Olthoi" for 25+ minutes without one swing: ghosts,
// objects the client still drew but the server no longer had for him (see GhostCheck.cs). Each
// was blacklisted for 30 s at a time, round and round, with navigation never getting a turn.
// Now a target that shows no swing after the step-1 re-issue, hasn't moved and that the server
// has said nothing about for GhostCheck.NoUpdateMs is a ghost: skipped until the server shows
// it is real (an update, a create, it moves) or the character changes landblock, and removed
// from the client when the engine can (plugin API v83 RemoveClientObject).
private readonly GhostCheck _ghostCheck = new();
internal readonly GhostTracker Ghosts = new();
private int _ghostsSkippedInScan; // ghosts the last scan passed over (lock log)
private GhostSpot? _lockSpot; // where the locked target was when locked
private uint _ghostLandblock;
private int _attacksSinceEvidence; // melee/missile attacks sent since the last hit, miss or kill
private bool _rebindThisTick; // AttackTarget sent a rebind CancelAttack this tick
private DateTime _lastAnimatingAt = DateTime.MinValue; // the motion queue last read busy (a swing playing)
private DateTime _lastPlayerMovedAt = DateTime.MinValue; // the character last moved QuietMoveM
private DateTime _lastQuietSampleAt = DateTime.MinValue;
private double _moveAnchorX, _moveAnchorY, _moveAnchorZ;
private const double QuietNoAnimMs = 1500; // no swing playing for this long
private const double QuietStillMs = 1000; // and standing still this long
private const double QuietMoveM = 0.3;
private DateTime _stallToggleAt = DateTime.MinValue; // step 3 sent peace; the flip back follows
private DateTime _lastMissileNoAmmoAt = DateTime.MinValue; // missile mode waiting on ammo is not a stall
private int _stallRewieldId; // step 4 in progress (weapon id)
@ -787,6 +823,9 @@ public partial class CombatManager : IDisposable
PickedWeaponWieldLoc = weaponWieldLoc,
HasWieldedAmmoFlag = hasAmmo,
LastCombatSkipReason = LastCombatSkipReason,
ScriptHookOwner = CombatHook.IsActive(RynthAiCombat.KindsAll) ? CombatHook.Owner : "",
ScriptHookKinds = CombatHook.IsActive(RynthAiCombat.KindsAll) ? CombatHook.Kinds : 0,
ScriptHook = CombatHook.Describe(),
};
}
@ -817,6 +856,11 @@ public partial class CombatManager : IDisposable
public int PickedWeaponWieldLoc;
public bool HasWieldedAmmoFlag;
public string LastCombatSkipReason;
/// <summary>The script holding the combat hook (RynthAi.Combat), "" when none; and its kinds (RynthAiCombat.Kind* bits).</summary>
public string ScriptHookOwner;
public uint ScriptHookKinds;
/// <summary>The hook's one-line summary (owner, lease, per-kind counters).</summary>
public string ScriptHook;
}
/// <summary>
@ -888,6 +932,14 @@ public partial class CombatManager : IDisposable
bool hasPlayerPos = _host.TryGetObjectPosition((uint)playerId, out uint meCell,
out float meX, out float meY, out float meZ);
// Ghosts that moved are real after all; a new landblock lets them all go.
_ghostsSkippedInScan = 0;
if (Ghosts.Count > 0)
{
if (hasPlayerPos) Ghosts.OnPlayerLandblock(meCell >> 16);
Ghosts.CheckMoved(TargetSpot);
}
foreach (var wo in _worldFilter.GetLandscape())
{
if (wo.Id == playerId) continue;
@ -932,15 +984,21 @@ public partial class CombatManager : IDisposable
// out of range and now cost only their distance, not the name list, blacklist,
// attackable and health reads as well.
bool isEngaged = wo.Id != 0 && (wo.Id == activeTargetId || wo.Id == _lockedTargetId);
if (dist > (isEngaged ? Math.Max(maxDist, DisengageDistance) : maxDist)) continue;
// Target lock (/ra targetlock): the player picked this one; the name list and
// Priority 0 don't keep it out (attackable, alive and LOS still do).
bool isForced = wo.Id != 0 && wo.Id == ForcedTargetId;
if (dist > (isEngaged || isForced ? Math.Max(maxDist, DisengageDistance) : maxDist)) continue;
// User-configured "never attack" list — excluded from acquisition
// entirely (an already-engaged match drops out of _scannedTargets
// here and is released by the scan-grace timer in Think).
if (IsUserBlacklistedName(wo.Name)) continue;
if (!isForced && IsUserBlacklistedName(wo.Name)) continue;
if (_blacklistManager.IsBlacklisted(wo.Id)) continue;
// A ghost (the server doesn't have it for us): skipped until it shows it is real.
if (Ghosts.IsGhost(wo.Id)) { _ghostsSkippedInScan++; continue; }
// Just killed (KillerNotification) but not yet a corpse — skip so we
// don't re-lock and cast at it during its death animation.
if (_recentlyKilled.ContainsKey(wo.Id)) continue;
@ -950,6 +1008,13 @@ public partial class CombatManager : IDisposable
// Dead but not yet reclassified as corpse — skip
if (_worldFilter.GetHealthRatio(wo.Id) == 0f) continue;
// Monster rule Priority 0 = IGNORE, with no exception: even one attacking us is never
// attacked (a monster worth fighting back needs a rule above 0). Left out of the
// scan entirely, so it is neither a target nor a reason to hold nav,
// combat, looting or buffs: every consumer reads this list or _nearbyNoLos, and an
// ignored monster is not counted in either (it is dropped before the LOS check).
if (!isForced && PriorityOf(wo.Id) <= 0) continue;
bool losBlocked = false;
if (_settings.EnableRaycasting && RaycastInitialized && _raycastSystem?.TargetingFSM != null)
{
@ -1007,6 +1072,7 @@ public partial class CombatManager : IDisposable
// Diagnostic: surface every blacklist (any path) with id + reason so a
// single login test is conclusive instead of another guess.
_blacklistManager.Log = m => _host.Log($"[Blacklist] {m}");
Ghosts.Cleared = (id, why) => _host.Log($"[Ghost] 0x{(uint)id:X8} '{_worldFilter[id]?.Name}' is real after all ({why}) - targetable again.");
ElementTracker = new WeaponElementTracker(host);
}
@ -1034,6 +1100,7 @@ public partial class CombatManager : IDisposable
_recentlyKilled.Remove(id);
_hitAt.Remove(id);
_blacklistManager.ForgetTarget(id);
Ghosts.NoteDeleted(id);
if (id == activeTargetId || id == _lockedTargetId || id == _lastAttackedTargetId)
_awaitingCastResolution = false;
@ -1100,6 +1167,29 @@ public partial class CombatManager : IDisposable
// chat-confirmation handler can record the cast against the right target
// for blacklist judgement — even if activeTargetId has since changed.
private int _pendingOffensiveTargetId = 0;
// The UseDone count at the pending offensive cast's send, and its answer (-1 = not seen yet).
private int _pendingOffensiveSeqAtSend;
private long _pendingOffensiveErr = -1;
/// <summary>Casts the server refused 'too busy' that were kept out of the no-damage count (tests, status).</summary>
internal int RefusedCastsNotJudged { get; private set; }
private void NoteOffensiveSeq()
{
_pendingOffensiveSeqAtSend = _host.HasUseDoneSeq ? _host.GetUseDoneSeq() : 0;
_pendingOffensiveErr = -1;
}
/// <summary>The first UseDone after the pending offensive cast's send is its answer.</summary>
private void ObserveOffensiveAnswer()
{
if (_pendingOffensiveErr >= 0 || !_host.HasUseDoneSeq) return;
try
{
if (_host.TryGetLastUseDone(out int seq, out uint err) && seq == _pendingOffensiveSeqAtSend + 1)
_pendingOffensiveErr = err;
}
catch { }
}
private const double OFFENSIVE_NOCHAT_TIMEOUT_MS = 5000.0;
// ACE doesn't emit "You cast X" chat for offensive war magic, so we infer
// a successful server cast by NEGATION: if no "You're too busy!" arrives
@ -1530,6 +1620,9 @@ public partial class CombatManager : IDisposable
// BuffManager's categorisation so a war spell the char can't actually
// cast gets marked unresolvable and FindBestOffensiveSpellId drops to
// an alternative, instead of silently re-firing the dead spell forever.
// A script's cast (RynthAi.Combat) is remembered on its own: it may not have armed the
// pending judgement (an area, nojudge or off-target cast) yet must not be re-cast forever.
NoteScriptCastRefusal(text);
if (_pendingOffensiveSpellId != 0)
{
string lo = text.ToLowerInvariant();
@ -1791,6 +1884,7 @@ public partial class CombatManager : IDisposable
DateTime now = DateTime.Now;
_lastSwingEvidenceAt = now;
_lastSwingEvidenceKind = kind;
_attacksSinceEvidence = 0;
switch (kind)
{
case "hit": _lastHitAt = now; break;
@ -1938,6 +2032,21 @@ public partial class CombatManager : IDisposable
FlightRecorderSignal.Dump(_host, $"casts with no damage at 0x{(uint)tid:X8}");
}
/// <summary>
/// For the no-damage blacklist: <paramref name="tid"/> is the locked target, no swing evidence
/// came since it was locked (not a hit or evade on anything), it hasn't moved since, and the
/// server has said nothing about it for <see cref="GhostCheck.NoUpdateMs"/>.
/// </summary>
private bool LooksLikeGhost(int tid, out double silentMs)
{
silentMs = -1;
if (tid == 0 || tid != _lockedTargetId || _targetLockedAt == DateTime.MinValue) return false;
if (_lastSwingEvidenceAt >= _targetLockedAt) return false;
if (_lockSpot == null || TargetSpot(tid) is not GhostSpot now || now.MovedFrom(_lockSpot.Value)) return false;
silentMs = ServerSilentMs(tid, DateTime.Now);
return silentMs < 0 || silentMs >= GhostCheck.NoUpdateMs;
}
private void JudgePendingCast()
{
if (_pendingJudgeCastAt == DateTime.MinValue) return;
@ -1956,6 +2065,12 @@ public partial class CombatManager : IDisposable
if (_consecutiveCastMisses >= _settings.BlacklistAttempts)
{
if (CurrentCombatMode == CombatMode.Magic) ReportNoDamageCasts(tid);
if (CurrentCombatMode != CombatMode.Magic && LooksLikeGhost(tid, out double silentMs))
{
_consecutiveCastMisses = 0;
MarkGhost(tid, _worldFilter[tid]?.Name, silentMs, $"{_settings.BlacklistAttempts} attacks with no swing, no hit and no evade");
return;
}
_blacklistManager.ReportFailure(tid);
if (_blacklistManager.IsBlacklisted(tid))
{
@ -1984,9 +2099,24 @@ public partial class CombatManager : IDisposable
if (_pendingOffensiveSpellId == 0) return;
if (_pendingOffensiveTargetId == 0) return;
if (_pendingOffensiveCastAt == DateTime.MinValue) return;
ObserveOffensiveAnswer();
if ((DateTime.Now - _pendingOffensiveCastAt).TotalMilliseconds < OffensiveRefusalWindowMs)
return;
// A refusal is not a cast (in a client log, three healthy targets were blacklisted 'after 3
// no-damage casts' whose casts had all come back UseDone 0x1D):
// the answer 0x1D, or no answer yet while the server is taken as busy, is not judged.
bool refused = _pendingOffensiveErr == ActionPacer.TooBusyErr || (_pendingOffensiveErr < 0 && ActionPacer.ServerBusy);
if (refused)
{
RefusedCastsNotJudged++;
_host.Log($"[Blacklist] cast at 0x{(uint)_pendingOffensiveTargetId:X8} {(_pendingOffensiveErr >= 0 ? "refused 'too busy' (UseDone 0x1D)" : "unanswered while the server is busy")}: not counted as a no-damage cast");
_pendingOffensiveSpellId = 0;
_pendingOffensiveTargetId = 0;
_pendingOffensiveCastAt = DateTime.MinValue;
return;
}
// Refusal window passed without a "too busy" — the server accepted
// the gesture. Queue this cast for blacklist judgement.
int targetId = _pendingOffensiveTargetId;
@ -2623,6 +2753,15 @@ public partial class CombatManager : IDisposable
/// <summary>The least Attack Spell Delay on an engine without the server gates.</summary>
internal const double NoGatesAttackFloorMs = 250;
/// <summary>Melee/missile: the first attack at a new target, with the server gates (see
/// <see cref="AttackIntervalMs"/>).</summary>
internal const double NewTargetPhysicalFloorMs = 200;
/// <summary>Melee/missile: the attack after a CancelAttack (attack rebind or stall re-issue).
/// ACE answers the cancel within a server tick or two; a swing still playing holds the attack
/// through the busy count, so the full 1000 ms interval is not needed here.</summary>
internal const double AttackAfterCancelMs = 300;
/// <summary>True when <see cref="BusyCount"/> is positive only because AC lowered it inline at a
/// server UseDone the busy hook can't see (see <see cref="CombatBusyGate"/>).</summary>
internal bool BusyIsLeftover()
@ -2643,10 +2782,16 @@ public partial class CombatManager : IDisposable
/// server gates (UseDone and the cast gesture): those already hold the cast until the
/// previous one is finished, so the new target only waits <see cref="NewTargetCastFloorMs"/>.
/// Casting at the same target keeps the full setting.
/// Melee/missile at a new target with the server gates: <see cref="NewTargetPhysicalFloorMs"/>.
/// The 1000 ms is the re-assert cadence for the target being fought; the first swing at the
/// next one only waited out what was left of it ([CombatLatency] "interval 9xx" on most locks,
/// Drakkon 2026-10-12), while the busy count already holds the attack until the last swing's
/// AttackDone and an attack still bound to a live old target is released first (rebind).
/// </summary>
internal static double AttackIntervalMs(int combatMode, int attackSpellIntervalMs, bool hasServerGates, bool newTarget)
{
if (combatMode != CombatMode.Magic) return 1000.0;
if (combatMode != CombatMode.Magic)
return newTarget && hasServerGates ? NewTargetPhysicalFloorMs : 1000.0;
// 0 is allowed (2026-10-08): no delay of its own, the server gates (UseDone and the cast
// gesture) alone hold the next cast until the last one is done. A file without the setting
// keeps 1500 (the payload is nullable). An engine without those gates keeps a 250 ms floor,
@ -2684,6 +2829,7 @@ public partial class CombatManager : IDisposable
private bool ThinkCore()
{
_rebindThisTick = false;
if (!_settings.EnableCombat) return false;
// A stall-watchdog re-wield must finish (weapon back in hand) before anything
@ -2775,6 +2921,12 @@ public partial class CombatManager : IDisposable
if (blacklisted)
DropTarget("blacklisted");
else if (target != null && activeTargetId != ForcedTargetId && PriorityOf(activeTargetId) <= 0)
{
// The rule says ignore (it changed, or the rule cache caught up).
ForgetScanned(activeTargetId);
DropTarget("ignored (monster rule Priority 0)");
}
else if (target != null && IsSpellProjectileName(target.Name))
DropTarget("spell projectile (not a monster)");
else if (target != null && (int)target.ObjectClass != (int)AcObjectClass.Monster)
@ -2919,12 +3071,13 @@ public partial class CombatManager : IDisposable
// wield, attack or cast while the server is still answering the last action (a kit, a corpse
// use, a buff, the last stance change). On ACE a mode change cancels a pending use's walk
// and fails a cast in progress; that interleaving began every stuck-use stall on record.
// Melee/missile attack repeats skip the animation gate (gestureGate false): the server swings
// Melee/missile attack repeats skip the animation and settle gates and the 'too busy' latch (ACE
// sends no UseDone for a swing, so a latch set by a refused pickup would starve them): the server swings
// on its own timers, a swing can't land inside a use's server turn because the use above holds
// every attack until it is answered, and waiting for each swing animation would cost DPS. A
// stance change still waits (ChangeCombatModeFor), and so does everything in peace/magic.
bool attackRepeat = CurrentCombatMode == CombatMode.Melee || CurrentCombatMode == CombatMode.Missile;
if (!ActionPacer.MayStart(_host, "Combat", HealNeed.None, out _, gestureGate: !attackRepeat))
if (!ActionPacer.MayStart(_host, "Combat", HealNeed.None, out _, animationGate: !attackRepeat, settleGate: !attackRepeat, attackRepeat: attackRepeat))
{
LastCombatSkipReason = "server-answering"; // D4 record-only
_tickWait = CombatLatencyTracker.Wait.Busy;
@ -3141,6 +3294,15 @@ public partial class CombatManager : IDisposable
return true;
}
// Waiting on a script's choice of spell (RynthAi.Combat): nothing was sent. The same
// as the wall hold: the attack interval doesn't start, the target and scan stay as they
// are, and the next tick asks again (bounded by the request's deadline).
if (_scriptHeld)
{
_tickWait = CombatLatencyTracker.Wait.Other;
return true;
}
// Don't restore the physical weapon on top of a cast just issued this tick
// (AttackWithMagic → MarkCombatCastIssued): the UseObject + re-equip below would
// truncate the in-flight gesture and strand Player.IsBusy. Defer one windup
@ -3225,6 +3387,10 @@ public partial class CombatManager : IDisposable
RecordOffensiveCast(activeTargetId);
lastAttackCmd = DateTime.Now;
_lastAttackCmdTargetId = activeTargetId;
// A rebind sent only the CancelAttack: the attack follows as soon as the cancel can
// have landed, not a whole interval later ("lock->attack 1750 ms (interval 1671)").
if (!physicalSent && _rebindThisTick)
lastAttackCmd = AttackAfterCancel(lastAttackCmd);
// Predicted kill shot (set in AttackWithMagic): the cast we just fired
// is expected to finish this mob. DON'T swap yet — on ACE a war cast is
@ -3313,7 +3479,22 @@ public partial class CombatManager : IDisposable
return false;
}
var act = _stallWatch.Tick(now, eligible, _lastSwingEvidenceAt, out double stalledMs);
bool quiet = SampleMeleeQuiet(now, eligible && mode == CombatMode.Melee);
// After the step-1 re-issue: still no swing, not moved, nothing from the server = a ghost.
if (_ghostCheck.IsArmed)
{
int tid = activeTargetId;
double silent = ServerSilentMs(tid, now);
if (_ghostCheck.Check(tid, now, _lastSwingEvidenceAt, TargetSpot(tid), silent) == GhostCheck.Verdict.Ghost)
{
MarkGhost(tid, targetObj.Name, silent, $"no swing after {_attacksSinceEvidence} attack(s) and a re-issue");
lastAttackCmd = now;
return true;
}
}
var act = _stallWatch.Tick(now, eligible, _lastSwingEvidenceAt, out double stalledMs, quiet);
switch (act)
{
case CombatStallWatchdog.StallAction.None:
@ -3341,10 +3522,14 @@ public partial class CombatManager : IDisposable
switch (act)
{
case CombatStallWatchdog.StallAction.Reissue:
{
ReleaseServerAttack("stall watchdog", log: false);
lastAttackCmd = now; // the attack goes out again one cycle later, after the cancel lands
_host.Log($"{head} re-issue: CancelAttack, attack 0x{activeTargetId:X8} again next cycle");
lastAttackCmd = AttackAfterCancel(now); // the attack goes out again once the cancel has landed
_ghostCheck.Arm(activeTargetId, now, TargetSpot(activeTargetId));
_host.Log($"{head} re-issue: CancelAttack, attack 0x{activeTargetId:X8} again next cycle" +
(_stallWatch.LastFireWasEarly ? $" (early: {stalledMs / 1000:0.0}s with no swing playing and the character standing still)" : ""));
return true;
}
case CombatStallWatchdog.StallAction.Reselect:
{
@ -3363,13 +3548,22 @@ public partial class CombatManager : IDisposable
// Same effect on the server as the wand heal: a mode change runs
// HandleActionCancelAttack. EquipWeaponAndSetStance flips back after its
// stance retry delay (~1 s with the flip backoff reset).
_host.ChangeCombatModeFor(CombatMode.NonCombat, "Combat/Stall", "stall watchdog: toggle the mode", force: true);
_stallToggleAt = now;
ResetStanceFlipBackoff();
lastStanceAttempt = now;
_serverAttackTargetId = 0;
lastAttackCmd = now;
_host.Log($"{head} toggle mode: peace, then back to {CombatModeName(mode)} on the next stance pass");
// Only a toggle the engine accepted starts the flip-back bookkeeping. A refusal (a teleport,
// a death) leaves it untouched and takes the ladder step back (Unfire), so it spends no step
// and the toggle is asked for again next tick.
if (_host.ChangeCombatModeFor(CombatMode.NonCombat, "Combat/Stall", "stall watchdog: toggle the mode", force: true))
{
_stallToggleAt = now;
ResetStanceFlipBackoff();
lastStanceAttempt = now;
_serverAttackTargetId = 0;
_host.Log($"{head} toggle mode: peace, then back to {CombatModeName(mode)} on the next stance pass");
lastAttackCmd = now;
}
else
{
_stallWatch.Unfire();
}
return true;
case CombatStallWatchdog.StallAction.Rewield:
@ -3382,6 +3576,117 @@ public partial class CombatManager : IDisposable
private CombatStallWatchdog.StallAction _lastStallStep = CombatStallWatchdog.StallAction.None;
/// <summary>How long the server has said nothing about <paramref name="id"/>: the engine's
/// record (plugin API v83) when it has one, else the plugin's own OnUpdateObject/OnCreateObject
/// record; -1 when neither has any.</summary>
internal double ServerSilentMs(int id, DateTime now)
{
if (_host.HasGetObjectServerAge)
{
int age = _host.GetObjectServerAge((uint)id);
if (age >= 0) return age;
}
return Ghosts.SilentMs(id, now);
}
/// <summary>
/// <paramref name="id"/> is a ghost: logged once, skipped by targeting until the server shows
/// it is real or the landblock changes, dropped as the target, and removed from the client
/// when the engine can (v83). Its no-damage blacklist entry, if any, is dropped (the ghost
/// mark outlives it).
/// </summary>
internal void MarkGhost(int id, string? name, double silentMs, string why)
{
if (id == 0) return;
uint pid = _playerId != 0 ? _playerId : _host.GetPlayerId();
uint lb = pid != 0 && _host.TryGetObjectPosition(pid, out uint pc, out _, out _, out _) ? pc >> 16 : 0;
GhostSpot spot = TargetSpot(id) ?? new GhostSpot(double.NaN, double.NaN, double.NaN);
Ghosts.Mark(id, name ?? "", spot, lb, DateTime.Now);
_blacklistManager.ClearFailure(id);
string silent = silentMs < 0 ? "nothing from the server about it since it was first seen" : $"nothing from the server about it for {silentMs / 1000:0}s";
_host.Log($"[Ghost] 0x{id:X8} '{name}' is a ghost: {why}, {silent}, it hasn't moved [{DescribeTargetPos(id)}]. " +
$"Skipped until the server sends anything about it or the landblock changes (ghosts now: {Ghosts.Count}).");
if (id == activeTargetId || id == _lockedTargetId)
DropTarget("ghost (the server doesn't have it)");
if (_host.HasRemoveClientObject)
{
int r = _host.RemoveClientObject((uint)id);
_host.Log($"[Ghost] 0x{id:X8}: " + r switch
{
1 => "removed from the client",
2 => "removal queued (AC's main thread)",
-1 => "not removed: the client's DeleteObject isn't bound yet (no delete since the engine loaded)",
_ => "not removed: the engine refused (see the engine log)",
});
}
}
/// <summary>The server sent an update for <paramref name="objectId"/> (RynthAiPlugin.OnUpdateObject).</summary>
public void OnServerObjectUpdate(uint objectId) => Ghosts.NoteServerUpdate((int)objectId, DateTime.Now);
/// <summary>The server created <paramref name="objectId"/> (RynthAiPlugin.OnCreateObject).</summary>
public void OnObjectCreated(uint objectId) => Ghosts.NoteServerUpdate((int)objectId, DateTime.Now, "the server created it again");
/// <summary>
/// Samples the swing animation and the character's position every stall-watch tick and says
/// whether melee is plainly stuck: at least two attacks sent since the last hit, miss or kill,
/// nothing animating for <see cref="QuietNoAnimMs"/> and the character not moving for
/// <see cref="QuietStillMs"/>. A swing in progress animates and a server move-to to the target
/// moves the character, so neither reads as quiet. False without the engine's motion read.
/// </summary>
private bool SampleMeleeQuiet(DateTime now, bool melee)
{
if (!_host.HasGetCastBusyState) return false;
// A gap (combat paused, a loot run): start the clocks over rather than read the gap as quiet.
if (_lastQuietSampleAt == DateTime.MinValue || (now - _lastQuietSampleAt).TotalMilliseconds > CombatStallWatchdog.TickGapResetMs)
{
_lastAnimatingAt = now;
_lastPlayerMovedAt = now;
_moveAnchorX = double.NaN;
}
_lastQuietSampleAt = now;
bool animating;
try { animating = _host.GetCastBusyState() != 0; } catch { animating = true; }
if (animating) _lastAnimatingAt = now;
uint pid = _playerId != 0 ? _playerId : _host.GetPlayerId();
if (pid != 0 && _host.TryGetObjectPosition(pid, out uint pc, out float px, out float py, out float pz))
{
double gx = ((pc >> 24) & 0xFF) * 192.0 + px, gy = ((pc >> 16) & 0xFF) * 192.0 + py;
if (double.IsNaN(_moveAnchorX))
{
_moveAnchorX = gx; _moveAnchorY = gy; _moveAnchorZ = pz;
}
else
{
double dx = gx - _moveAnchorX, dy = gy - _moveAnchorY, dz = pz - _moveAnchorZ;
if (dx * dx + dy * dy + dz * dz > QuietMoveM * QuietMoveM)
{
_moveAnchorX = gx; _moveAnchorY = gy; _moveAnchorZ = pz;
_lastPlayerMovedAt = now;
}
}
}
else _lastPlayerMovedAt = now; // no position: never call it standing still
return melee
&& _attacksSinceEvidence >= 2
&& (now - _lastAnimatingAt).TotalMilliseconds >= QuietNoAnimMs
&& (now - _lastPlayerMovedAt).TotalMilliseconds >= QuietStillMs;
}
/// <summary>Where a target is (landblock-global x/y and z), or null.</summary>
private GhostSpot? TargetSpot(int id)
{
if (id == 0 || !_host.TryGetObjectPosition((uint)id, out uint c, out float x, out float y, out float z)) return null;
return new GhostSpot(((c >> 24) & 0xFF) * 192.0 + x, ((c >> 16) & 0xFF) * 192.0 + y, z);
}
/// <summary>The lastAttackCmd stamp that lets the next melee/missile attack go
/// <see cref="AttackAfterCancelMs"/> after <paramref name="now"/> (the interval is 1000 ms there).</summary>
private static DateTime AttackAfterCancel(DateTime now) => now.AddMilliseconds(AttackAfterCancelMs - 1000.0);
/// <summary>Stall watchdog / attack-rebind counters for /ra why.</summary>
public int StallEpisodes => _stallWatch.Episodes;
public int StallRecoveries => _stallWatch.Recoveries;
@ -3652,6 +3957,7 @@ public partial class CombatManager : IDisposable
public void HandleCombatTrigger()
{
if (_scannedTargets.Count == 0) return;
if (TryLockForcedTarget()) return; // Target lock (/ra targetlock): CombatManager.TargetLock.cs
DateTime now = TargetClock();
double acquireRange = Math.Max(1.0, _settings.MonsterRange);
@ -3739,14 +4045,20 @@ public partial class CombatManager : IDisposable
// One line per real switch. A switch should be a genuine event (target died, left,
// or a higher priority showed up; with the lock off, something clearly better). If
// this floods the log, selection is thrashing again.
int bestPriority = PriorityOf(best.Id);
LockTarget(best, bestPriority, $"{SchemeName(scheme)}: {DescribeSchemeValue(scheme, best)}, priority {bestPriority}, {DescribeTargetPos(best.Id)}", switchWhy);
}
/// <summary>Makes <paramref name="best"/> the fight target (one log line; the switch says why).</summary>
private void LockTarget(ScannedTarget best, int bestPriority, string picked, string? switchWhy)
{
int bestId = best.Id;
int bestPriority = PriorityOf(bestId);
string picked = $"{SchemeName(scheme)}: {DescribeSchemeValue(scheme, best)}, priority {bestPriority}, {DescribeTargetPos(bestId)}";
if (_lockedTargetId != 0)
_host.Log($"[CombatTarget] switch 0x{_lockedTargetId:X8} '{_worldFilter[_lockedTargetId]?.Name}' ({switchWhy}, {DescribeTargetPos(_lockedTargetId)}) " +
$"-> 0x{bestId:X8} '{_worldFilter[bestId]?.Name}' ({picked})");
else
_host.Log($"[CombatTarget] lock 0x{bestId:X8} '{_worldFilter[bestId]?.Name}' ({picked})");
_host.Log($"[CombatTarget] lock 0x{bestId:X8} '{_worldFilter[bestId]?.Name}' ({picked})" +
(_ghostsSkippedInScan > 0 ? $" [{_ghostsSkippedInScan} ghost(s) in range skipped]" : ""));
// [CombatLatency]: time this engagement from the lock to its first attack.
double lockMs = Environment.TickCount64;
@ -3757,9 +4069,10 @@ public partial class CombatManager : IDisposable
_lockedTargetId = bestId;
_lockedPriority = bestPriority;
_targetLockedAt = DateTime.Now;
_lockSpot = TargetSpot(bestId);
_lastDamageDealtAt = DateTime.MinValue;
_lockedLastSeen = best; // it was in this tick's scan: the grace covers a blink next tick
_lockedLastSeenInScan = now;
_lockedLastSeenInScan = TargetClock();
_consecutiveCastMisses = 0;
_pendingJudgeCastAt = DateTime.MinValue;
_facingTarget = false;
@ -3860,6 +4173,9 @@ public partial class CombatManager : IDisposable
return progress != DateTime.MinValue && (now - progress).TotalMilliseconds <= UndamagedCommitmentMaxMs;
}
/// <summary>True when the monster rule for <paramref name="id"/> says Priority 0 (never attacked).</summary>
internal bool IsIgnored(int id) => id != ForcedTargetId && PriorityOf(id) <= 0;
/// <summary>The Priority of the monster rule that applies to <paramref name="id"/> (its own
/// row by name or match expression, else the DEFAULT row; 1 when neither exists). Cached per
/// monster for <see cref="PriorityCacheMs"/>; the cache empties when the rule list changes.</summary>
@ -4039,14 +4355,33 @@ public partial class CombatManager : IDisposable
/// <summary>The Items list's usable weapons, in list order, with their kind, element, rending and whether each is in hand.</summary>
internal List<WeaponCandidate> ListedCandidates()
{
var list = ListedCandidates(admitCasters: false, out List<int>? leftOut);
// A script choosing the attack spells (RynthAi.Combat) can attack with a caster whatever
// War/Void training says, but only when the list has no melee/missile weapon to use:
// a fighter's listed buff wand must not pull it out of melee.
if (list.Count == 0 && leftOut != null && ScriptPicksAttack)
return ListedCandidates(admitCasters: true, out _);
if (list.Count == 0 && leftOut != null)
foreach (int id in leftOut)
if (_wandRejectedNoted.Add(id))
_host.Log($"[EquipDiag] caster 0x{(uint)id:X8} '{_worldFilter[id]?.Name}' is not a combat weapon: {CanMagicDiag()}");
return list;
}
/// <param name="admitCasters">Take listed casters even with War and Void untrained.</param>
/// <param name="leftOut">The casters skipped for that (null when none).</param>
private List<WeaponCandidate> ListedCandidates(bool admitCasters, out List<int>? leftOut)
{
leftOut = null;
int inHand = InHandWeaponId();
var list = new List<WeaponCandidate>();
foreach (var r in _settings.ItemRules)
{
if (r.Id == 0 || !IsUsableCombatWeapon(r.Id)) continue;
if (list.Any(c => c.Id == r.Id)) continue;
if (r.Id == 0) continue;
var wo = _worldFilter[r.Id];
if (wo == null) continue;
if (!admitCasters && !IsUsableCombatWeapon(r.Id)) { (leftOut ??= new List<int>()).Add(r.Id); continue; }
if (list.Any(c => c.Id == r.Id)) continue;
if (wo.ObjectClass == AcObjectClass.MissileWeapon && IsAmmoItem(wo)) continue; // listed arrows are the ammo choice, never a weapon to wield
if (IsShieldItem(wo)) continue; // listed shields are the off hand's (CombatManager.Offhand.cs)
var info = ElementTracker.Read(r.Id, wo.Name);
@ -4128,13 +4463,23 @@ public partial class CombatManager : IDisposable
return any ? CreatureWeakness.FromAppraisal(m) : null;
}
/// <summary>
/// Optional UtilityBelt damage seed lookup (wcid, name) → damage types best first, or null.
/// Set by the plugin when the seed store loads; null (default) leaves the ranking as before.
/// Called on the combat thread.
/// </summary>
internal Func<uint, string, IReadOnlyList<string>?>? MobSeedLookup { get; set; }
/// <summary>The same by wcid and name; <paramref name="objectId"/> (optional) reads a live creature type.</summary>
internal CreatureWeakness.Ranking? WeaknessFor(uint wcid, string? name, int objectId = 0)
{
name ??= "";
int ctype = CreatureTypeOf(wcid, name, objectId);
string learned = wcid != 0 ? _damageStore?.GetBestElement(wcid) ?? "" : "";
return CreatureWeakness.Rank(wcid, name, ctype, learned);
IReadOnlyList<string>? seeded = null;
try { seeded = MobSeedLookup?.Invoke(wcid, name); }
catch { seeded = null; } // a bad seed file must never stop element choice
return CreatureWeakness.Rank(wcid, name, ctype, learned, seeded);
}
// Server replies seen when the last combat wield was sent (UseDone / WeenieError sequence).
@ -4148,7 +4493,7 @@ public partial class CombatManager : IDisposable
{
DateTime now = DateTime.Now;
if (SwapTracker.PendingId != 0 && ServerRefusedSinceSend()) SwapTracker.Refused(now, WeaponName);
var step = SwapTracker.Next(chosenId, inHandId, now, WeaponName);
var step = SwapTracker.Next(chosenId, inHandId, now, WeaponName, forKey: activeTargetId);
if (SwapTracker.Notice != null)
{
_host.Log($"[EquipDiag] {SwapTracker.Notice}");
@ -4290,7 +4635,7 @@ public partial class CombatManager : IDisposable
if ((DateTime.Now - _lastEquipDiagAt).TotalSeconds > 5)
{
_lastEquipDiagAt = DateTime.Now;
_host.Log($"[EquipDiag] no weapon found (source=none, desired='{desired}', ItemRules={_settings.ItemRules.Count}, MonsterRule='{rule?.Name ?? "null"}') — proceeding unarmed");
_host.Log($"[EquipDiag] no weapon found (source=none, desired='{desired}', ItemRules={_settings.ItemRules.Count}, MonsterRule='{rule?.Name ?? "null"}', {CanMagicDiag()}) - proceeding unarmed");
}
return EnsureUnarmedStance();
}
@ -4447,9 +4792,15 @@ public partial class CombatManager : IDisposable
// watchdog won't) and RE-EQUIP the wand (UseObject resyncs the wield; on a
// truly-unwielded wand it wields it, which is the actual fix). Without this
// the bot sat in NonCombat for 5h, buffs expired, never fighting (2026-06-10).
if (_stanceStuckSince == DateTime.MinValue)
// The clock starts when a stance request has actually gone out (below), never on refusals
// (see BuffManager's _buffStanceStuckSince): a clock counting through them ends in a re-equip.
// A refusal newer than the clock's start: the request that started it was dropped (a teleport), so restart the clock.
if (_stanceStuckSince != DateTime.MinValue && ActionPacer.LastEngineRefusalMs > _stanceStuckStartMs)
{
_stanceStuckSince = DateTime.Now;
double stuckMs = (DateTime.Now - _stanceStuckSince).TotalMilliseconds;
_stanceStuckStartMs = ActionPacer.NowMs();
}
double stuckMs = _stanceStuckSince == DateTime.MinValue ? 0 : (DateTime.Now - _stanceStuckSince).TotalMilliseconds;
// RE-EQUIP recovery — only for the first couple of attempts in an
// episode (handles a stale "wielded reads true" on a wand that
// actually isn't wielded). Capped: UseObject on a genuinely wielded
@ -4485,6 +4836,7 @@ public partial class CombatManager : IDisposable
if ((DateTime.Now - lastStanceAttempt).TotalMilliseconds > StanceRetryDelayMs()
&& _host.ChangeCombatModeFor(desiredMode, "Combat", "stance"))
{
if (_stanceStuckSince == DateTime.MinValue) { _stanceStuckSince = DateTime.Now; _stanceStuckStartMs = ActionPacer.NowMs(); }
if (diagNow) { _lastEquipDiagAt = DateTime.Now; _host.Log($"[EquipDiag] wielded=true mode={CurrentCombatMode}→{desiredMode} (weapon=0x{targetWeaponId:X8} '{weaponObj.Name}' src={weaponSource}) — sending ChangeCombatMode"); }
lastStanceAttempt = DateTime.Now;
NoteStanceFlipSent();
@ -5216,6 +5568,7 @@ public partial class CombatManager : IDisposable
&& !IsKnownDead(_serverAttackTargetId))
{
_attackRebinds++;
_rebindThisTick = true;
ReleaseServerAttack($"target is now 0x{targetId:X8} '{_worldFilter[activeTargetId]?.Name}' {DescribeTargetPos(activeTargetId)}", log: true);
LastCombatSkipReason = "attack-rebind";
return false;
@ -5252,6 +5605,7 @@ public partial class CombatManager : IDisposable
RynthCore.Plugin.Shared.ActionPacer.NoteAttackSent(); // nothing else starts before this swing plays
_serverAttackTargetId = activeTargetId;
_attacksSinceEvidence++;
LastCombatSkipReason = "attack"; // D4 record-only: physical attack sent this tick
return true;
}
@ -5299,6 +5653,7 @@ public partial class CombatManager : IDisposable
{
_wallFaceHeld = false;
_manaCastHeld = false;
_scriptHeld = false;
if (_spellManager == null || target == null) return;
// Hard safety veto: never cast offensive magic at something AC's combat
@ -5399,6 +5754,11 @@ public partial class CombatManager : IDisposable
}
}
// A script chooses this cast (RynthAi.Combat, CombatManager.ScriptHook.cs): ask it, wait for
// its answer (held, not an attack yet), cast what it chose; a decline, a bad answer or no
// answer in time falls through to RynthAi's own choice below, this same tick.
if (TryScriptAttack(target, element)) return;
if (rule != null && PickBaseShape(rule) < 0)
{
_host.Log($"[CombatCast] rule '{rule.Name}' has no attack shapes enabled (UseArc/Ring/Streak/Bolt/Blast/Wall all false) — no offensive cast");
@ -5464,6 +5824,7 @@ public partial class CombatManager : IDisposable
_pendingOffensiveSpellId = offensiveSpellId;
_pendingOffensiveCastAt = DateTime.Now;
_pendingOffensiveTargetId = activeTargetId;
NoteOffensiveSeq();
// Tag this cast's weapon + element + tier so the pushed damage event
// can be attributed to it, count it for casts-to-kill learning, then
@ -5596,13 +5957,32 @@ public partial class CombatManager : IDisposable
private static bool IsWandObject(WorldObject wo) => WeaponList.IsWand(wo);
/// <summary>War or Void Magic trained — the character can attack with a caster.
/// Skills not read yet count as trained, like the other skill gates here.</summary>
private bool CanAttackWithMagic =>
/// <summary>War or Void Magic trained. Skills not read yet count as trained, like the
/// other skill gates here.</summary>
private bool AttackMagicTrained =>
_charSkills == null
|| _charSkills[AcSkillType.WarMagic].Training >= 2
|| _charSkills[AcSkillType.VoidMagic].Training >= 2;
/// <summary>A script holds the attack kind (RynthAi.Combat): it picks the attack spell, from
/// any school, so a caster is the combat weapon whatever War/Void training says.</summary>
private static bool ScriptPicksAttack => CombatHook.IsActive(RynthAiCombat.KindAttack);
/// <summary>The character can attack with a caster: War or Void Magic trained, or a script
/// choosing the attack spells (a Life-only caster whose script drains, for one). Gates the
/// wand fallback when no weapon was chosen; the Items list itself admits a caster under the
/// hook only when it has no melee/missile weapon (ListedCandidates).</summary>
private bool CanAttackWithMagic => AttackMagicTrained || ScriptPicksAttack;
/// <summary>For the [EquipDiag] lines: canMagic and whether the script hook made it true.</summary>
private string CanMagicDiag()
{
bool trained = AttackMagicTrained, hook = ScriptPicksAttack;
return $"canMagic={trained || hook}" + (hook && !trained ? " (script attack hook)" : "");
}
private readonly HashSet<int> _wandRejectedNoted = new();
/// <summary>A weapon combat may fight with: anything the character has (in the world
/// cache) but a caster when the character has no attack magic. Debuff casting picks its
/// wand separately. An id missing from the cache is not a candidate: a weapon that was
@ -5613,7 +5993,7 @@ public partial class CombatManager : IDisposable
{
var wo = _worldFilter[id];
if (wo == null) return false;
return CanAttackWithMagic || !IsWandObject(wo);
return AttackMagicTrained || !IsWandObject(wo);
}
private static List<string> BuildDebuffList(MonsterRule rule, string element)

View file

@ -29,6 +29,12 @@ internal sealed class CombatStallWatchdog
/// real stalls ran 12-49 s.</summary>
public const double StallMs = 6000;
/// <summary>Melee that is plainly stuck - attacks sent, no swing playing, the character
/// standing still (CombatManager.SampleMeleeQuiet) - gets step 1 after this instead (Drakkon
/// 2026-10-12: the server's move-to the target stalled 2 m short; the cancel 6 s later fixed
/// it at once every time, so most of the 7-9 s per stall was the wait).</summary>
public const double QuietStallMs = 2500;
/// <summary>Time allowed for each step to show a swing before the next one.</summary>
public const double StepMs = 3000;
@ -47,6 +53,7 @@ internal sealed class CombatStallWatchdog
private DateTime _lastStepAt = DateTime.MinValue;
private DateTime _cooldownUntil = DateTime.MinValue;
private int _step; // steps fired in the current episode (0 = none)
private DateTime _prevStepAt = DateTime.MinValue; // _lastStepAt before the newest Fire (for Unfire)
private DateTime _stallRef = DateTime.MinValue; // last swing (or episode start) before the stall
/// <summary>Episodes where the watchdog acted (diagnostics / status).</summary>
@ -55,14 +62,18 @@ internal sealed class CombatStallWatchdog
public int Recoveries { get; private set; }
/// <summary>The last step fired in the current episode (0 = none).</summary>
public int CurrentStep => _step;
/// <summary>The episode's step 1 fired on <see cref="QuietStallMs"/> rather than <see cref="StallMs"/>.</summary>
public bool LastFireWasEarly { get; private set; }
public static int StepCount => 4;
/// <summary>
/// Advance the watchdog. <paramref name="eligible"/> is the full precondition set;
/// <paramref name="lastEvidenceAt"/> the last hit, miss or kill. Returns the step to
/// carry out now (or Recovered / GaveUp for logging), with the stalled time.
/// <paramref name="lastEvidenceAt"/> the last hit, miss or kill. <paramref name="quiet"/>:
/// the caller sees no swing playing and the character standing still (step 1 after
/// <see cref="QuietStallMs"/>). Returns the step to carry out now (or Recovered / GaveUp for
/// logging), with the stalled time.
/// </summary>
public StallAction Tick(DateTime now, bool eligible, DateTime lastEvidenceAt, out double stalledMs)
public StallAction Tick(DateTime now, bool eligible, DateTime lastEvidenceAt, out double stalledMs, bool quiet = false)
{
stalledMs = 0;
bool gap = _lastTick != DateTime.MinValue
@ -96,7 +107,9 @@ internal sealed class CombatStallWatchdog
if (_step == 0)
{
if (stalledMs < StallMs) return StallAction.None;
bool early = quiet && stalledMs >= QuietStallMs;
if (stalledMs < StallMs && !early) return StallAction.None;
LastFireWasEarly = stalledMs < StallMs;
Episodes++;
_stallRef = refAt;
return Fire(now);
@ -122,6 +135,7 @@ internal sealed class CombatStallWatchdog
private StallAction Fire(DateTime now)
{
_step++;
_prevStepAt = _lastStepAt;
_lastStepAt = now;
return _step switch
{
@ -132,6 +146,16 @@ internal sealed class CombatStallWatchdog
};
}
/// <summary>Take back the step just returned because the caller could not carry it out (the engine refused the mode change):
/// a refusal spends no ladder step. The ladder returns to where it was, so the step fires again on the next tick.</summary>
public void Unfire()
{
if (_step <= 0) return;
_step--;
_lastStepAt = _prevStepAt;
if (_step == 0 && Episodes > 0) Episodes--;
}
private void ResetEpisode()
{
_eligibleSince = DateTime.MinValue;

View file

@ -348,12 +348,40 @@ public class FellowshipTracker : IDisposable
int bufPtr = Marshal.ReadInt32(addr);
if (bufPtr == 0) return "";
IntPtr strAddr = new IntPtr(bufPtr + 0x14);
if (!IsReadablePointer(strAddr)) return "";
string? raw = Marshal.PtrToStringAnsi(strAddr);
if (raw == null) return "";
if (raw.Length > 64) raw = raw[..64];
return raw;
// Bounded read: PtrToStringAnsi scans to a NUL however far that is, past
// the probed region into unmapped memory if the buffer is mid-free or never terminated.
return ReadBoundedAnsi(strAddr, MaxNameChars, ReadableBytesFrom(strAddr));
}
catch { return ""; }
}
/// <summary>A fellowship member's name is at most this long (AC names are under 20).</summary>
internal const int MaxNameChars = 64;
/// <summary>Bytes from <paramref name="ptr"/> to the end of its committed region (the probed
/// page run); 0 when the address is not readable.</summary>
internal static int ReadableBytesFrom(IntPtr ptr)
{
if (ptr == IntPtr.Zero) return 0;
if (VirtualQuery(ptr, out var mbi, Marshal.SizeOf<MEMORY_BASIC_INFORMATION>()) == 0) return 0;
if (mbi.State != MEM_COMMIT) return 0;
if ((mbi.Protect & PAGE_NOACCESS) != 0 || (mbi.Protect & PAGE_GUARD) != 0) return 0;
long left = (long)mbi.BaseAddress + (long)mbi.RegionSize - (long)ptr;
return left <= 0 ? 0 : (int)Math.Min(left, int.MaxValue);
}
/// <summary>
/// Reads a NUL-terminated ANSI string of at most <paramref name="maxChars"/> characters and
/// never more than <paramref name="readableBytes"/> bytes from <paramref name="addr"/>. An
/// unterminated run is cut at the bound, not scanned on. Internal for the tests.
/// </summary>
internal static unsafe string ReadBoundedAnsi(IntPtr addr, int maxChars, int readableBytes)
{
int limit = Math.Min(maxChars, readableBytes);
if (addr == IntPtr.Zero || limit <= 0) return "";
byte* p = (byte*)addr;
int n = 0;
while (n < limit && p[n] != 0) n++;
return n == 0 ? "" : Marshal.PtrToStringAnsi(addr, n) ?? "";
}
}

View file

@ -0,0 +1,166 @@
using System;
using System.Collections.Generic;
namespace RynthCore.Plugin.RynthAi;
// ── Ghost creatures (Drakkon 2026-10-12, Olthoi in 0x6146) ───────────────────────────────────
// A ghost is an object the client still draws but the server no longer has for this player.
// Drakkon stood for 25+ minutes swinging at four of them: the engine's flight recorder shows every
// MeleeAttack answered within ~35 ms by AttackDone ActionCancelled, no CombatCommenceAttack, no
// motion; the "monsters" never moved, never died, and the server sent nothing about them after the
// character walked past at 20:58:15. A real Olthoi that walked up at 21:27 was killed in 6 s. The
// no-damage blacklist dropped each ghost for 30 s, so with four of them around the bot went round
// and round and navigation never got a turn.
/// <summary>A point in landblock-global coordinates (x/y across landblocks, z as is).</summary>
internal readonly record struct GhostSpot(double X, double Y, double Z)
{
/// <summary>Movement (m) that means the object is alive on the server.</summary>
public const double MovedM = 0.05;
public bool MovedFrom(GhostSpot other)
{
double dx = X - other.X, dy = Y - other.Y, dz = Z - other.Z;
return dx * dx + dy * dy + dz * dz > MovedM * MovedM;
}
}
/// <summary>
/// The verdict on one stalled target, armed when the stall watchdog's step 1 (CancelAttack + attack
/// again) goes out. Ghost once <see cref="AnswerWaitMs"/> passed with no swing evidence since the
/// re-issue, the same target, not moved, and the server silent about it for <see cref="NoUpdateMs"/>
/// (a monster fighting anyone nearby gets motion updates every few seconds; even an idle one
/// answers an attack with a turn and a swing). Pure.
/// </summary>
internal sealed class GhostCheck
{
public const double AnswerWaitMs = 1500;
public const double NoUpdateMs = 8000;
public enum Verdict { None, Alive, Ghost }
private int _target;
private DateTime _at;
private GhostSpot? _spot;
public bool IsArmed => _target != 0;
public void Arm(int targetId, DateTime now, GhostSpot? spot)
{
if (targetId == 0 || spot == null) { Disarm(); return; }
_target = targetId;
_at = now;
_spot = spot;
}
public void Disarm()
{
_target = 0;
_spot = null;
}
/// <summary>
/// <paramref name="serverSilentMs"/>: how long the server has said nothing about the target
/// (-1 = unknown: no record since the engine and the plugin started watching, which for an
/// object the client already had means nothing either).
/// </summary>
public Verdict Check(int targetId, DateTime now, DateTime lastEvidenceAt, GhostSpot? spot, double serverSilentMs)
{
if (_target == 0) return Verdict.None;
if (targetId != _target || lastEvidenceAt > _at || spot == null || spot.Value.MovedFrom(_spot!.Value)
|| (serverSilentMs >= 0 && serverSilentMs < (now - _at).TotalMilliseconds))
{
Disarm();
return Verdict.Alive; // a swing, a move, a server message since the re-issue, or another target
}
if ((now - _at).TotalMilliseconds < AnswerWaitMs) return Verdict.None;
Disarm();
return serverSilentMs < 0 || serverSilentMs >= NoUpdateMs ? Verdict.Ghost : Verdict.Alive;
}
}
/// <summary>
/// The ghosts found this session. A ghost is skipped by targeting until the server shows it is
/// real after all (any update or create for its id, or it moves) or the character changes
/// landblock - not for a fixed time. Its server-update clock is kept here too, for engines before
/// plugin API v83 (no GetObjectServerAge). Pump thread only.
/// </summary>
internal sealed class GhostTracker
{
public readonly record struct Ghost(int Id, string Name, GhostSpot Spot, uint Landblock, DateTime MarkedAt);
private readonly Dictionary<int, Ghost> _ghosts = new();
private readonly Dictionary<int, DateTime> _lastUpdate = new();
private readonly List<int> _scratch = new();
private const int MaxUpdateEntries = 8192;
/// <summary>Called with (id, why) when a ghost turns out real or is forgotten.</summary>
public Action<int, string>? Cleared;
public int Count => _ghosts.Count;
public IEnumerable<Ghost> All => _ghosts.Values;
public int MarkedTotal { get; private set; }
public bool IsGhost(int id) => id != 0 && _ghosts.ContainsKey(id);
public void Mark(int id, string name, GhostSpot spot, uint landblock, DateTime now)
{
if (id == 0) return;
if (!_ghosts.ContainsKey(id)) MarkedTotal++;
_ghosts[id] = new Ghost(id, name, spot, landblock, now);
}
/// <summary>The server sent something about <paramref name="id"/> (OnUpdateObject / OnCreateObject).</summary>
public void NoteServerUpdate(int id, DateTime now, string what = "the server sent an update for it")
{
if (id == 0) return;
if (_lastUpdate.Count >= MaxUpdateEntries && !_lastUpdate.ContainsKey(id)) _lastUpdate.Clear();
_lastUpdate[id] = now;
if (_ghosts.Remove(id)) Cleared?.Invoke(id, what);
}
public void NoteDeleted(int id)
{
_lastUpdate.Remove(id);
_ghosts.Remove(id);
}
/// <summary>Milliseconds since the plugin last saw a server update for <paramref name="id"/>, -1 none.</summary>
public double SilentMs(int id, DateTime now)
=> _lastUpdate.TryGetValue(id, out DateTime t) ? Math.Max(0, (now - t).TotalMilliseconds) : -1;
/// <summary>Ghosts that moved are real: cleared. <paramref name="spotOf"/> null = no position.</summary>
public void CheckMoved(Func<int, GhostSpot?> spotOf)
{
if (_ghosts.Count == 0) return;
_scratch.Clear();
foreach (Ghost g in _ghosts.Values)
if (spotOf(g.Id) is GhostSpot s && s.MovedFrom(g.Spot)) _scratch.Add(g.Id);
foreach (int id in _scratch)
{
_ghosts.Remove(id);
Cleared?.Invoke(id, "it moved");
}
}
/// <summary>The character is in <paramref name="landblock"/> (high 16 bits of the cell): ghosts
/// marked in another landblock are let go.</summary>
public void OnPlayerLandblock(uint landblock)
{
if (_ghosts.Count == 0 || landblock == 0) return;
_scratch.Clear();
foreach (Ghost g in _ghosts.Values)
if (g.Landblock != landblock) _scratch.Add(g.Id);
foreach (int id in _scratch)
{
_ghosts.Remove(id);
Cleared?.Invoke(id, "the character changed landblock");
}
}
public void Clear()
{
_ghosts.Clear();
_lastUpdate.Clear();
}
}

View file

@ -223,7 +223,9 @@ public class MissileCraftingManager
_combinesCompleted = 0;
_allCombinesDone = false;
try { _host.ChangeCombatModeFor(CombatMode.NonCombat, "Crafting", "missile crafting needs peace mode"); } catch { }
_peaceSent = false;
_peaceAskedAt = DateTime.Now; // the wait for the stance counts from the first ask
TryPeaceForCrafting();
var headItems = inv.Where(i => recipe.IsHead(i.Name)).ToList();
var shaftItems = inv.Where(i => recipe.IsShaft(i.Name)).ToList();
@ -258,6 +260,22 @@ public class MissileCraftingManager
// COMBINING
// ══════════════════════════════════════════════════════════════════
private bool _peaceSent;
private DateTime _peaceAskedAt;
private const double PeaceWaitMaxMs = 2500;
/// <summary>Asks for Peace mode until the engine accepts (a refusal is retried, not counted as sent).</summary>
private void TryPeaceForCrafting()
{
if (_peaceSent) return;
try
{
if (_host.HasGetCurrentCombatMode && _host.GetCurrentCombatMode() == CombatMode.NonCombat) { _peaceSent = true; return; }
_peaceSent = _host.ChangeCombatModeFor(CombatMode.NonCombat, "Crafting", "missile crafting needs peace mode");
}
catch { }
}
private void ProcessCombining()
{
if (_allCombinesDone)
@ -283,6 +301,12 @@ public class MissileCraftingManager
return;
}
if (!_peaceSent)
{
TryPeaceForCrafting();
if (!_peaceSent && (DateTime.Now - _peaceAskedAt).TotalMilliseconds < PeaceWaitMaxMs) return; // still asking, inside the ceiling
}
if ((DateTime.Now - _lastApplyAttempt).TotalMilliseconds >= APPLY_RETRY_MS)
{
try

View file

@ -91,6 +91,26 @@ internal sealed class PetManager
internal static Func<long> Clock { get; set; } = static () => Environment.TickCount64;
private static long NowMs => Clock();
/// <summary>
/// Optional ILT Hub hook: when it returns true an EMPTY essence is used anyway, because
/// the server's Summon Essence Refill Charm refills it from banked pyreals on use.
/// Null (default) keeps the retail behaviour (spirit refill or park).
/// </summary>
public Func<bool>? AllowSummonOnEmpty { get; set; }
/// <summary>
/// Optional ILT Hub hook: while it returns true no combat summon is started (e.g. the
/// healing-pet helper has its heal pet out). Null (default) never holds.
/// </summary>
public Func<bool>? HoldSummons { get; set; }
/// <summary>
/// Optional ILT Hub hook, called when a pet already holds the slot and monsters are near.
/// Returns true after dismissing a non-combat (cosmetic) pet so a combat pet can follow.
/// Null (default) leaves whatever pet is out alone.
/// </summary>
public Func<bool>? YieldPetForCombat { get; set; }
public PetManager(RynthCoreHost host, LegacyUiSettings settings,
WorldObjectCache objectCache, CombatManager? combat,
CharacterSkills? skills)
@ -129,7 +149,7 @@ internal sealed class PetManager
bool spiritGone = _activeSpiritId != 0 && _objectCache[_activeSpiritId] == null;
if (spiritGone || DeviceHasCharges(_activeDeviceId))
{
_host.Log($"[RynthAi] Pet: refill complete (essence 0x{(uint)_activeDeviceId:X8}).");
RynthLog.Write(LogCat.Pets, $"[RynthAi] Pet: refill complete (essence 0x{(uint)_activeDeviceId:X8}).");
GoIdle();
}
}
@ -138,7 +158,7 @@ internal sealed class PetManager
// decrement that never lands), and waiting on it would wedge the subsystem.
if (_state != PetState.Idle && now - _actionIssuedAt > ActionTimeoutMs)
{
_host.Log($"[RynthAi] Pet: action timeout in {_state} after {now - _actionIssuedAt}ms (essence 0x{(uint)_activeDeviceId:X8}); cooling down.");
RynthLog.Write(LogCat.Pets, $"[RynthAi] Pet: action timeout in {_state} after {now - _actionIssuedAt}ms (essence 0x{(uint)_activeDeviceId:X8}); cooling down.");
if (_activeDeviceId != 0)
_deviceCooldownUntil[_activeDeviceId] = now + DeviceFailCooldownMs;
// A summon that we simply couldn't confirm very likely DID work — assume
@ -176,6 +196,10 @@ internal sealed class PetManager
{
_host.Log($"[RynthAi] Pet: essence 0x{(uint)_activeDeviceId:X8} reports empty; will refill.");
_serverSaidFullUntil.Remove(_activeDeviceId); // really empty: the read is right again
// The server-side pyreal refill didn't happen (charm off / no pyreals):
// park the essence so the empty-summon path can't spin on it.
if (AllowSummonOnEmpty?.Invoke() == true && _activeDeviceId != 0)
_deviceCooldownUntil[_activeDeviceId] = NowMs + DeviceNoSpiritCooldownMs;
GoIdle();
return;
}
@ -203,7 +227,14 @@ internal sealed class PetManager
{
// A pet is already up (just summoned, or detected in the world) — done.
if (now < _assumePetActiveUntil) return;
if (IsPetActive()) return;
if (IsPetActive())
{
// A cosmetic pet in the slot steps aside for the fight; wait for the dismiss to land.
if (YieldPetForCombat != null && MonstersNearby() && YieldPetForCombat())
_assumePetActiveUntil = now + 3000;
return;
}
if (HoldSummons?.Invoke() == true) return;
// Only summon when mobs are near (the user's trigger).
if (!MonstersNearby()) return;
@ -237,7 +268,15 @@ internal sealed class PetManager
return;
}
// charges == 0 → empty. Auto-refill from an Encapsulated Spirit.
// charges == 0 → empty. ILT shards with an active pyreal-refill charm refill
// the essence server-side on use, so summon straight away.
if (AllowSummonOnEmpty?.Invoke() == true)
{
IssueSummon(deviceId, charges);
return;
}
// Otherwise auto-refill from an Encapsulated Spirit.
if (_settings.PetAutoRefill)
{
int spiritId = FindEncapsulatedSpirit();
@ -267,7 +306,7 @@ internal sealed class PetManager
_activeSpiritId = 0;
_preActionCharges = charges;
_actionIssuedAt = NowMs;
_host.Log($"[RynthAi] Pet: summoning from essence 0x{(uint)deviceId:X8} (charges={charges}).");
RynthLog.Write(LogCat.Pets, $"[RynthAi] Pet: summoning from essence 0x{(uint)deviceId:X8} (charges={charges}).");
_host.UseFor(unchecked((uint)deviceId), "Pet", "summon a pet from the essence");
}

View file

@ -0,0 +1,232 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Reflection;
namespace RynthCore.Plugin.RynthAi;
/// <summary>One spell from ACECustom's spell catalog (Combat\SpellCatalog.tsv).</summary>
internal sealed class SpellCatalogEntry
{
public int Id;
public string Name = "";
/// <summary>Spell level 1-8 (ACE Spell.Level from Power vs SpellFormula.MinPower).</summary>
public int Level;
/// <summary>Buff, Debuff, Heal, Harm, Neutral, Projectile or Utility.</summary>
public string Effect = "";
/// <summary>Self, Other, Item or Fellowship.</summary>
public string Target = "";
/// <summary>ACE SpellCategory: spells in one family don't stack, the highest power wins.</summary>
public int FamilyId;
public string FamilyName = "";
public int Power;
/// <summary>Seconds, or -1 for spells without a duration.</summary>
public int DurationSec;
/// <summary>Creature Enchantment, Life Magic, Item Enchantment, War Magic or Void Magic.</summary>
public string School = "";
public int Mana;
public string Description = "";
public bool IsBuff => Effect.Equals("Buff", StringComparison.OrdinalIgnoreCase);
public bool IsSelf => Target.Equals("Self", StringComparison.OrdinalIgnoreCase);
public bool IsItemTarget => Target.Equals("Item", StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// ACECustom's spell catalog (generated by Tools\Generate-SpellCatalog.ps1 from ACECustom
/// Reports\SpellCatalog-Full.csv). It is the spell list of the Spells window and buff profiles:
/// level, school, Self/Other/Item target and spell family per spell id.
/// </summary>
internal static class SpellCatalog
{
private const string ResourceName = "RynthCore.Plugin.RynthAi.Combat.SpellCatalog.tsv";
/// <summary>The five magic schools, in the order the UI lists them.</summary>
public static readonly string[] Schools =
{
"Creature Enchantment", "Life Magic", "Item Enchantment", "War Magic", "Void Magic",
};
private static readonly object Gate = new();
private static List<SpellCatalogEntry> _all = new();
private static Dictionary<int, SpellCatalogEntry> _byId = new();
private static Dictionary<int, List<SpellCatalogEntry>> _byFamily = new();
private static Dictionary<string, SpellCatalogEntry> _byName = new(StringComparer.OrdinalIgnoreCase);
private static string[] _effects = Array.Empty<string>();
public static bool IsLoaded => _all.Count > 0;
public static IReadOnlyList<SpellCatalogEntry> All => _all;
/// <summary>Distinct effect types present in the catalog (Buff, Debuff, ...), sorted.</summary>
public static IReadOnlyList<string> Effects => _effects;
/// <summary>Loads the embedded catalog once. Safe to call repeatedly.</summary>
public static void EnsureLoaded(Action<string>? log = null)
{
if (IsLoaded) return;
lock (Gate)
{
if (IsLoaded) return;
try
{
using Stream? stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(ResourceName);
if (stream == null)
{
log?.Invoke($"[RynthAi] Spell catalog resource missing: {ResourceName}");
return;
}
using var reader = new StreamReader(stream, detectEncodingFromByteOrderMarks: true);
LoadFrom(reader);
}
catch (Exception ex)
{
log?.Invoke($"[RynthAi] Spell catalog load failed: {ex.Message}");
}
}
}
/// <summary>Parses catalog lines (tests feed their own). Replaces anything loaded before.</summary>
public static void LoadFrom(TextReader reader)
{
var all = new List<SpellCatalogEntry>(6400);
string? line;
while ((line = reader.ReadLine()) != null)
{
if (line.Length == 0 || line[0] == '#') continue;
string[] c = line.Split('\t');
if (c.Length < 11 || !int.TryParse(c[0], NumberStyles.Integer, CultureInfo.InvariantCulture, out int id))
continue;
all.Add(new SpellCatalogEntry
{
Id = id,
Name = c[1],
Level = ParseInt(c[2]),
Effect = c[3],
Target = c[4],
FamilyId = ParseInt(c[5]),
FamilyName = c[6],
Power = ParseInt(c[7]),
DurationSec = ParseInt(c[8]),
School = c[9],
Mana = ParseInt(c[10]),
Description = c.Length > 11 ? c[11] : "",
});
}
var byId = new Dictionary<int, SpellCatalogEntry>(all.Count);
var byFamily = new Dictionary<int, List<SpellCatalogEntry>>();
var byName = new Dictionary<string, SpellCatalogEntry>(StringComparer.OrdinalIgnoreCase);
var effects = new SortedSet<string>(StringComparer.OrdinalIgnoreCase);
foreach (var e in all)
{
byId[e.Id] = e;
if (e.FamilyId != 0)
{
if (!byFamily.TryGetValue(e.FamilyId, out var list)) byFamily[e.FamilyId] = list = new List<SpellCatalogEntry>();
list.Add(e);
}
// Several ids share a name (e.g. mastery lines); the lowest id is the canonical one.
byName.TryAdd(e.Name, e);
if (e.Effect.Length > 0) effects.Add(e.Effect);
}
lock (Gate)
{
_byId = byId;
_byFamily = byFamily;
_byName = byName;
_effects = new List<string>(effects).ToArray();
_all = all;
}
}
public static SpellCatalogEntry? Get(int spellId) =>
_byId.TryGetValue(spellId, out var e) ? e : null;
public static SpellCatalogEntry? GetByName(string name) =>
!string.IsNullOrEmpty(name) && _byName.TryGetValue(name, out var e) ? e : null;
/// <summary>Every spell in a family (empty when the family is unknown).</summary>
public static IReadOnlyList<SpellCatalogEntry> Family(int familyId) =>
_byFamily.TryGetValue(familyId, out var list) ? list : (IReadOnlyList<SpellCatalogEntry>)Array.Empty<SpellCatalogEntry>();
/// <summary>
/// True for an Item Enchantment buff: it lands on armor or a weapon, not on the player,
/// so its timer can only come from the cast's chat line. Unknown names are false.
/// </summary>
public static bool IsItemSchoolBuff(string name)
{
var e = GetByName(name);
return e != null && e.IsBuff && e.School.Equals("Item Enchantment", StringComparison.OrdinalIgnoreCase);
}
/// <summary>Casting skill for a school name; CreatureEnchantment when unrecognised.</summary>
public static AcSkillType SkillForSchool(string school) => school switch
{
"Life Magic" => AcSkillType.LifeMagic,
"Item Enchantment" => AcSkillType.ItemEnchantment,
"War Magic" => AcSkillType.WarMagic,
"Void Magic" => AcSkillType.VoidMagic,
_ => AcSkillType.CreatureEnchantment,
};
/// <summary>Short school label for narrow table columns.</summary>
public static string ShortSchool(string school) => school switch
{
"Creature Enchantment" => "Creature",
"Life Magic" => "Life",
"Item Enchantment" => "Item",
"War Magic" => "War",
"Void Magic" => "Void",
_ => school,
};
private static readonly string[] TierSuffixes = { " VIII", " VII", " VI", " IV", " V", " III", " II", " I" };
/// <summary>
/// A spell name without its tier: "Strength Self VI" → "Strength Self",
/// "Incantation of Blade Bane" → "Blade Bane", "Aura of Blood Drinker Self III" →
/// "Blood Drinker Self", "Impenetrability Incantation" → "Impenetrability".
/// Names without a tier (lore spells) come back unchanged.
/// </summary>
public static string StripTier(string name)
{
string n = (name ?? "").Trim();
if (n.StartsWith("Incantation of ", StringComparison.OrdinalIgnoreCase)) n = n.Substring("Incantation of ".Length);
if (n.StartsWith("Aura of ", StringComparison.OrdinalIgnoreCase)) n = n.Substring("Aura of ".Length);
if (n.EndsWith(" Incantation", StringComparison.OrdinalIgnoreCase)) n = n.Substring(0, n.Length - " Incantation".Length);
foreach (string s in TierSuffixes)
{
if (n.EndsWith(s, StringComparison.Ordinal))
{
n = n.Substring(0, n.Length - s.Length);
break;
}
}
return n.Trim();
}
/// <summary>
/// The buffing key for a spell: the base name buffing resolves to the best tier the character
/// knows ("Strength Self"). A Self or Item spell is its own ladder; for an Other spell
/// (including lore and server-custom names like "Might of the Lugians") the family's lowest
/// Self ladder is used, then its Item ladder, so buffing casts the self-castable form.
/// </summary>
public static string BuffKeyFor(SpellCatalogEntry e)
{
if (e.IsSelf || e.IsItemTarget) return StripTier(e.Name);
SpellCatalogEntry? self = null, item = null;
foreach (var m in Family(e.FamilyId))
{
if (!m.IsBuff) continue;
if (m.IsSelf && (self == null || m.Level < self.Level || (m.Level == self.Level && m.Id < self.Id))) self = m;
else if (m.IsItemTarget && (item == null || m.Level < item.Level || (m.Level == item.Level && m.Id < item.Id))) item = m;
}
return StripTier((self ?? item ?? e).Name);
}
private static int ParseInt(string s) =>
int.TryParse(s, NumberStyles.Integer, CultureInfo.InvariantCulture, out int v) ? v : 0;
}

File diff suppressed because it is too large Load diff

View file

@ -94,6 +94,24 @@ public static class SpellDatabase
return $"Unknown Spell ({spellId})";
}
/// <summary>Spell family and difficulty (power). False when the spell isn't in SpellData.txt.</summary>
public static bool TryGetSpellMeta(int spellId, out int family, out int difficulty)
{
if (_spellMeta.TryGetValue(spellId, out var meta))
{
family = meta.Category;
difficulty = meta.Power;
return true;
}
family = 0;
difficulty = 0;
return false;
}
/// <summary>True when the spell id is in the embedded table or the built-in recall list.</summary>
public static bool HasSpell(int spellId) =>
_spellNames.ContainsKey(spellId) || _builtinSpells.ContainsKey(spellId);
public static string GetSpellNameOrId(int spellId)
{
if (_spellNames.TryGetValue(spellId, out string? name)) return name;

View file

@ -120,6 +120,8 @@ public class SpellManager
SpellDatabase.Load(msg => _host.WriteToChat(msg, 2));
SpellDictionary = SpellDatabase.BuildNameToIdMap();
_nameToIds = SpellDatabase.BuildNameToIdsMap();
// ACECustom catalog: school/level/target for the Spells window and buff profiles.
SpellCatalog.EnsureLoaded(msg => _host.WriteToChat(msg, 2));
_host.WriteToChat($"[RynthAi] Magic System Online: {SpellDictionary.Count} spells loaded.", 1);
}
catch (Exception ex)
@ -330,6 +332,19 @@ public class SpellManager
/// </summary>
public bool IsKnownSpellId(int id) => _knownSpellIds.Contains(id);
/// <summary>The next RefreshKnownSpells reads the spellbook at once (a spell was just learned).</summary>
public void InvalidateKnownSpells() => _lastKnownRefreshUtc = DateTime.MinValue;
/// <summary>
/// Copy of the known-spell snapshot for the render thread (the Spells window). Call it on the
/// pump thread: RefreshKnownSpells refills the live set in place there.
/// </summary>
public HashSet<int> CopyKnownSpellIds()
{
RefreshKnownSpells();
return new HashSet<int>(_knownSpellIds);
}
/// <summary>
/// Refresh the known-spell inventory from the engine's main-thread
/// spellbook snapshot (host ReadKnownSpells). Throttled. Safe no-op if the

View file

@ -13,8 +13,13 @@ namespace RynthCore.Plugin.RynthAi;
/// * Retry cap: a weapon that doesn't reach the hand after <see cref="MaxTries"/> sends is
/// rested for <see cref="GiveUpMs"/>; combat carries on with what's in hand (logged once).
/// * No flip-flop: having swapped A → B, swapping back to A within <see cref="MinDwellMs"/>
/// is held, and so is any swap once <see cref="MaxSwapsPerWindow"/> landed inside
/// <see cref="SwapWindowMs"/>. Combat keeps fighting with B.
/// for the same fight (the same <c>forKey</c>, the target) is held, and so is any swap once
/// <see cref="MaxSwapsPerWindow"/> landed inside <see cref="SwapWindowMs"/>. Combat keeps
/// fighting with B. A NEW target that wants A back gets it at once (2026-10-12, Drakkon:
/// Lightning Quadrelle for a Giant Maggot, then the next target, a Grub weak to Bludgeon,
/// was fought with the Quadrelle for 5-10 s until the 20 s dwell from the last swap ran out
/// - "he attacks for about 5 seconds with the wrong element weapon"). The window cap still
/// bounds a fight that alternates between two kinds of monster.
/// </summary>
internal sealed class WeaponSwapTracker
{
@ -44,6 +49,7 @@ internal sealed class WeaponSwapTracker
private readonly List<DateTime> _landed = new();
private int _lastFrom, _lastTo;
private DateTime _lastLandedAt = DateTime.MinValue;
private int _askKey, _pendingKey, _lastKey; // the fight (target id) each swap was for; 0 = unknown
/// <summary>The weapon a swap is in flight for (0 = none).</summary>
public int PendingId => _pendingId;
@ -56,11 +62,13 @@ internal sealed class WeaponSwapTracker
/// <summary>
/// What to do about <paramref name="chosenId"/> with <paramref name="inHandId"/> in hand
/// (0 = nothing readable in hand).
/// (0 = nothing readable in hand). <paramref name="forKey"/> is the fight the weapon is
/// chosen for (the target id; 0 = unknown, treated as the same fight as the last swap).
/// </summary>
public Step Next(int chosenId, int inHandId, DateTime now, Func<int, string>? nameOf = null)
public Step Next(int chosenId, int inHandId, DateTime now, Func<int, string>? nameOf = null, int forKey = 0)
{
HoldReason = "";
_askKey = forKey;
if (chosenId == 0) return Step.InHand;
if (inHandId == chosenId)
@ -84,7 +92,8 @@ internal sealed class WeaponSwapTracker
if (inHandId != 0)
{
if (chosenId == _lastFrom && inHandId == _lastTo && (now - _lastLandedAt).TotalMilliseconds < MinDwellMs)
bool sameFight = forKey == 0 || _lastKey == 0 || forKey == _lastKey;
if (sameFight && chosenId == _lastFrom && inHandId == _lastTo && (now - _lastLandedAt).TotalMilliseconds < MinDwellMs)
{
HoldReason = "just swapped away from it";
return Step.Hold;
@ -102,6 +111,7 @@ internal sealed class WeaponSwapTracker
/// <summary>A wield of <paramref name="id"/> was sent with <paramref name="fromId"/> in hand.</summary>
public void Sent(int id, int fromId, DateTime now)
{
_pendingKey = _askKey; // the fight the last Next was asked about
_pendingId = id;
_pendingFrom = fromId;
_pendingAt = now;
@ -129,6 +139,7 @@ internal sealed class WeaponSwapTracker
_landed.Clear();
_lastFrom = _lastTo = 0;
_lastLandedAt = DateTime.MinValue;
_askKey = _pendingKey = _lastKey = 0;
HoldReason = "";
Notice = null;
}
@ -139,6 +150,7 @@ internal sealed class WeaponSwapTracker
{
_lastFrom = _pendingFrom;
_lastTo = _pendingId;
_lastKey = _pendingKey;
_lastLandedAt = now;
_landed.Add(now);
}

View file

@ -1228,6 +1228,13 @@ public class WorldObjectCache
: defaultValue;
}
/// <summary>
/// True when ownership is readable and the object has neither a container nor a wielder,
/// so it lies loose in the world. Unreadable ownership is false (a pack item is never a ground drop).
/// </summary>
public bool IsOnGround(int id)
=> TryGetOwnership(id, out int containerId, out int wielderId, out _) && containerId == 0 && wielderId == 0;
public int GetContainerId(int id)
{
if (!TryGetOwnership(id, out int containerId, out _, out _))
@ -1780,6 +1787,42 @@ public class WorldObjectCache
return result;
}
/// <summary>
/// Items the client lists inside <paramref name="containerId"/> that the cache never
/// classified, looked up now (the indexer's lazy lookup files them) and returned.
/// <paramref name="known"/> is what <see cref="GetContainedItems"/> already found.
/// An item whose create the cache never processed is otherwise invisible to corpse
/// looting: it isn't in the inventory or landscape sets, so it is never a candidate
/// and the corpse is finished without it (2026-10-11, Silentkelpie: a Necrolytic
/// Extract on a corpse with a Keep rule, left behind with no log line; the cache
/// reported it DELETE-BEFORE-CLASSIFY when the corpse went away).
/// </summary>
public List<WorldObject> RescueContainedItems(int containerId, IReadOnlyCollection<WorldObject> known)
{
var rescued = new List<WorldObject>();
if (containerId == 0 || !_host.HasGetContainerContents) return rescued;
uint[] buf = new uint[256];
int count;
try { count = _host.GetContainerContents(unchecked((uint)containerId), buf); }
catch { return rescued; }
if (count <= 0) return rescued;
var have = new HashSet<int>();
foreach (var wo in known) have.Add(wo.Id);
for (int i = 0; i < Math.Min(count, buf.Length); i++)
{
int id = unchecked((int)buf[i]);
if (id == 0 || have.Contains(id)) continue;
WorldObject? wo = this[id];
if (wo == null) continue;
if (wo.ObjectClass == AcObjectClass.Corpse || wo.ObjectClass == AcObjectClass.Monster) continue;
rescued.Add(wo);
}
return rescued;
}
/// <summary>Enumerate landscape creatures (received health updates or TYPE_CREATURE).</summary>
public IEnumerable<WorldObject> GetLandscape()
{

View file

@ -0,0 +1,475 @@
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthAi;
/// <summary>
/// The script-provided combat hook (Shared/RynthAiCombatApi.cs): who holds it, for which kinds,
/// until when, and one request slot per kind. Static, like the interface table that serves it,
/// so it survives a re-Init of the plugin instance; everything runs on the plugin pump thread.
///
/// RynthAi asks (CombatManager.AttackWithMagic for an attack, BuffManager.CheckVitals for a heal)
/// with <see cref="Step"/>: the first call opens a request and says Wait; later calls say Wait
/// until the answer is in (Decided), the answer is a decline (Native), or the deadline passes
/// (Native). The hook is active only while its lease is live, so a script plugin that stops
/// renewing (unloaded, crashed, stopped) leaves RynthAi native within one lease.
/// </summary>
internal static class CombatHook
{
/// <summary>What a consumer does this tick.</summary>
internal enum Outcome { Native, Wait, Decided }
/// <summary>One kind's request slot.</summary>
internal sealed class Slot
{
public readonly uint Kind;
public Slot(uint kind) => Kind = kind;
public bool Open;
public CombatRequestV1 Request;
public bool Decided;
public uint DecidedSpell, DecidedTarget, DecidedFlags;
// The last decision consumed (handed back in the next request).
public uint LastSeq, LastSpell, LastTarget;
public long LastAtMs;
// The cast in flight (PendingSpell 0 = none), with the UseDone count at its send, and the
// most recent resolved cast with its final answer (ResolvedErr -1 = none could be read).
public uint PendingSeq, PendingSpell, PendingTarget;
public long PendingAtMs;
public int PendingSeqAtSend = -1;
// The UseDone count that answers it: one more than its send count, or than the answer of the
// cast still in flight before it (both kinds, in send order); -1 = unknown (time limit only).
public int PendingExpectSeq = -1;
public uint ResolvedSeq, ResolvedSpell, ResolvedTarget;
public long ResolvedAtMs;
public int ResolvedErr = -1;
/// <summary>The cast in flight is done: <paramref name="err"/> its answer (-1 = none read).</summary>
public void Resolve(int err)
{
if (PendingSpell == 0) return;
ResolvedSeq = PendingSeq; ResolvedSpell = PendingSpell; ResolvedTarget = PendingTarget;
ResolvedAtMs = PendingAtMs; ResolvedErr = err;
PendingSeq = PendingSpell = PendingTarget = 0; PendingAtMs = 0; PendingSeqAtSend = -1; PendingExpectSeq = -1;
InFlight.Remove(this);
}
// Counters for /ra combat and the tests.
public int Opened, Casts, Declines, Timeouts, Rejects;
public long LastTimeoutLogMs = long.MinValue;
public long LastRejectLogMs = long.MinValue;
public void Reset()
{
Open = false; Decided = false; Request = default;
DecidedSpell = DecidedTarget = DecidedFlags = 0;
LastSeq = LastSpell = LastTarget = 0; LastAtMs = 0;
PendingSeq = PendingSpell = PendingTarget = 0; PendingAtMs = 0; PendingSeqAtSend = -1; PendingExpectSeq = -1;
InFlight.Remove(this);
ResolvedSeq = ResolvedSpell = ResolvedTarget = 0; ResolvedAtMs = 0; ResolvedErr = -1;
Opened = Casts = Declines = Timeouts = Rejects = 0;
LastTimeoutLogMs = LastRejectLogMs = long.MinValue;
}
}
/// <summary>Milliseconds clock (Environment.TickCount64; the host tests replace it).</summary>
internal static Func<long> Clock = static () => Environment.TickCount64;
internal static long Now => Clock();
/// <summary>
/// The last UseDone (count, error), or null when the engine can't say: RynthAi sets it at Init. A
/// cast's answer is the first UseDone after its send (ctx.last.err).
/// </summary>
internal static Func<(int Seq, uint Err)?>? LastUseDone;
// The casts in flight of both kinds, in send order: the UseDones answer them in that order.
private static readonly List<Slot> InFlight = new(2);
/// <summary>
/// Resolves the casts in flight (each tick, at Poll, and before the next cast goes out), in send
/// order: each one's answer is the UseDone after its send, or after the answer of the cast sent
/// before it (an attack and a heal both in flight). A later count with that one unseen, or no
/// UseDone within RynthAiCombat.ResolveTimeoutMs, resolves it with no answer (-1).
/// </summary>
public static void ObserveUseDone()
{
if (InFlight.Count == 0) return;
(int Seq, uint Err)? last;
try { last = LastUseDone?.Invoke(); } catch { last = null; }
long now = Now;
for (int i = 0; i < InFlight.Count;)
{
Slot s = InFlight[i];
if (last is { } u && s.PendingExpectSeq >= 0 && u.Seq >= s.PendingExpectSeq)
{
s.Resolve(u.Seq == s.PendingExpectSeq ? unchecked((int)u.Err) : -1); // removes it
continue;
}
if (now - s.PendingAtMs >= RynthAiCombat.ResolveTimeoutMs) { s.Resolve(-1); continue; }
i++;
}
}
/// <summary>A timeout is logged at most this often per kind.</summary>
internal const long TimeoutLogIntervalMs = 60_000;
private const long RejectLogIntervalMs = 5_000;
/// <summary>A request this long past its deadline when RynthAi next asks is dropped and asked again.</summary>
internal const long StaleGraceMs = 1_000;
public static string Owner { get; private set; } = "";
public static uint Kinds { get; private set; }
public static long LeaseUntilMs { get; private set; }
public static uint AttackTimeoutMs { get; private set; } = RynthAiCombat.DefaultAttackTimeoutMs;
public static uint HealTimeoutMs { get; private set; } = RynthAiCombat.DefaultHealTimeoutMs;
public static readonly Slot Attack = new(RynthAiCombat.KindAttack);
public static readonly Slot Heal = new(RynthAiCombat.KindHeal);
private static uint _seq;
/// <summary>Forget everything (plugin shutdown, host tests).</summary>
public static void Reset()
{
Owner = "";
Kinds = 0;
LeaseUntilMs = 0;
AttackTimeoutMs = RynthAiCombat.DefaultAttackTimeoutMs;
HealTimeoutMs = RynthAiCombat.DefaultHealTimeoutMs;
Attack.Reset();
Heal.Reset();
_seq = 0;
}
public static Slot? SlotFor(uint kind) => kind == RynthAiCombat.KindAttack ? Attack : kind == RynthAiCombat.KindHeal ? Heal : null;
/// <summary>True while <paramref name="kind"/> is held and the lease is live.</summary>
public static bool IsActive(uint kind) => (Kinds & kind) != 0 && Now < LeaseUntilMs;
private static bool LeaseLive => Kinds != 0 && Now < LeaseUntilMs;
/// <summary>Takes or renews the hook. Returns the kinds granted (0 = another owner's lease is live).</summary>
public static uint Claim(uint kinds, uint leaseMs, uint attackTimeoutMs, uint healTimeoutMs, string owner)
{
owner = (owner ?? "").Trim();
if (owner.Length > RynthAiCombat.MaxOwnerLength) owner = owner.Substring(0, RynthAiCombat.MaxOwnerLength);
kinds &= RynthAiCombat.KindsAll;
long now = Now;
bool live = LeaseLive;
if (live && !string.Equals(Owner, owner, StringComparison.Ordinal)) return 0;
// Kinds this owner no longer claims: their open requests are dropped (native that tick).
uint dropped = live ? Kinds & ~kinds : RynthAiCombat.KindsAll;
if ((dropped & RynthAiCombat.KindAttack) != 0) Cancel(Attack);
if ((dropped & RynthAiCombat.KindHeal) != 0) Cancel(Heal);
if (kinds == 0)
{
Owner = "";
Kinds = 0;
LeaseUntilMs = 0;
return 0;
}
Owner = owner;
Kinds = kinds;
LeaseUntilMs = now + RynthAiCombat.ClampLease(leaseMs);
AttackTimeoutMs = RynthAiCombat.ClampTimeout(attackTimeoutMs, RynthAiCombat.DefaultAttackTimeoutMs);
HealTimeoutMs = RynthAiCombat.ClampTimeout(healTimeoutMs, RynthAiCombat.DefaultHealTimeoutMs);
return kinds;
}
/// <summary>Drops <paramref name="kinds"/> now; their open requests are cancelled.</summary>
public static void Release(uint kinds)
{
kinds &= RynthAiCombat.KindsAll;
if ((kinds & RynthAiCombat.KindAttack) != 0) Cancel(Attack);
if ((kinds & RynthAiCombat.KindHeal) != 0) Cancel(Heal);
Kinds &= ~kinds;
if (Kinds == 0) { Owner = ""; LeaseUntilMs = 0; }
}
/// <summary>1 when a request of <paramref name="kind"/> is open and unanswered (copied to <paramref name="request"/>).</summary>
public static bool Poll(uint kind, out CombatRequestV1 request)
{
request = default;
Slot? s = SlotFor(kind);
if (s == null || !IsActive(kind) || !s.Open || s.Decided || Now > s.Request.DeadlineMs) return false;
request = s.Request;
request.LastSeq = s.LastSeq;
request.LastSpell = s.LastSpell;
request.LastTarget = s.LastTarget;
request.LastAtMs = s.LastAtMs;
ObserveUseDone();
request.ResolvedSeq = s.ResolvedSeq;
request.ResolvedSpell = s.ResolvedSpell;
request.ResolvedTarget = s.ResolvedTarget;
request.ResolvedAtMs = s.ResolvedAtMs;
request.ResolvedErr = s.ResolvedSpell != 0 ? s.ResolvedErr : -1;
request.PendingSeq = s.PendingSeq;
request.PendingSpell = s.PendingSpell;
request.PendingTarget = s.PendingTarget;
request.PendingAtMs = s.PendingAtMs;
return true;
}
/// <summary>The answer to request <paramref name="seq"/>. False = stale.</summary>
public static bool Decide(uint seq, uint kind, uint spellId, uint targetId, uint flags)
{
Slot? s = SlotFor(kind);
if (s == null || !IsActive(kind) || !s.Open || s.Decided || s.Request.Seq != seq || Now > s.Request.DeadlineMs) return false;
s.Decided = true;
s.DecidedSpell = spellId;
s.DecidedTarget = targetId;
s.DecidedFlags = flags;
return true;
}
private static void Cancel(Slot s)
{
s.Open = false;
s.Decided = false;
}
/// <summary>
/// One consumer step for <paramref name="slot"/>. <paramref name="forTarget"/> is what the request
/// is about (the attack target; for a heal the fight target, informational, 0 when none): an open
/// attack request about another target is dropped and a fresh one opened; a heal request is not. <paramref name="build"/> fills a new request's context (RynthAi's
/// view of the fight); Seq, Kind, TargetId and the times are set here.
/// </summary>
public static Outcome Step(Slot slot, uint forTarget, Func<CombatRequestV1> build, Action<string>? log,
out uint spellId, out uint targetId, out uint flags)
{
spellId = targetId = flags = 0;
if (!IsActive(slot.Kind))
{
Cancel(slot);
return Outcome.Native;
}
long now = Now;
// An attack about another target: the target moved on, ask afresh. A heal's target is only
// informational (the fight target), so a heal request keeps its deadline when the fight
// target changes; restarting it would let a target swap every few hundred ms hold the
// heal past its 750 ms deadline for ever. Its answer is still checked against the targets
// as they are when it comes (BuffManager.ScriptHealProblem).
if (slot.Open && slot.Kind == RynthAiCombat.KindAttack && slot.Request.TargetId != forTarget) Cancel(slot);
// RynthAi stopped asking for a while (its gates held the cast, or health came back over the
// line): an answer, or a missing one, from back then is stale. Ask afresh, no timeout counted.
if (slot.Open && now > slot.Request.DeadlineMs + StaleGraceMs) Cancel(slot);
if (!slot.Open)
{
CombatRequestV1 r = build();
r.StructSize = (uint)Unsafe.SizeOf<CombatRequestV1>();
if (++_seq == 0) _seq = 1;
r.Seq = _seq;
r.Kind = slot.Kind;
r.TargetId = forTarget;
r.IssuedAtMs = now;
r.DeadlineMs = now + (slot.Kind == RynthAiCombat.KindAttack ? AttackTimeoutMs : HealTimeoutMs);
slot.Request = r;
slot.Open = true;
slot.Decided = false;
slot.Opened++;
return Outcome.Wait;
}
if (slot.Decided)
{
if (slot.DecidedSpell == 0)
{
Consume(slot, 0, 0);
slot.Declines++;
return Outcome.Native;
}
spellId = slot.DecidedSpell;
targetId = slot.DecidedTarget;
flags = slot.DecidedFlags;
return Outcome.Decided; // the consumer validates, then Cast or Reject
}
if (now > slot.Request.DeadlineMs)
{
Cancel(slot);
slot.Timeouts++;
if (slot.LastTimeoutLogMs == long.MinValue || now - slot.LastTimeoutLogMs >= TimeoutLogIntervalMs)
{
slot.LastTimeoutLogMs = now;
log?.Invoke($"[CombatHook] {RynthAiCombat.KindNames(slot.Kind)} request {slot.Request.Seq} unanswered after " +
$"{slot.Request.DeadlineMs - slot.Request.IssuedAtMs} ms ('{Owner}'): RynthAi chose instead " +
$"({slot.Timeouts} timeout(s) so far; logged at most once a minute)");
}
return Outcome.Native;
}
return Outcome.Wait;
}
/// <summary>
/// The decided spell went out (or was waited on): the request is done. <paramref name="seqAtSend"/>
/// is the UseDone count read just before the send (ActionPacer.LastCastSeqAtSend); -1 reads the
/// last UseDone now instead.
/// </summary>
public static void Cast(Slot slot, uint spellId, uint targetId, int seqAtSend = -1)
{
Consume(slot, spellId, targetId, seqAtSend);
if (spellId != 0) slot.Casts++; // 0: handled without a cast (a wand swap step in flight)
}
/// <summary>The decided spell failed RynthAi's checks: the request is done, RynthAi chooses.</summary>
public static void Reject(Slot slot, string why, Action<string>? log)
{
uint seq = slot.Request.Seq, spell = slot.DecidedSpell, target = slot.DecidedTarget;
Consume(slot, 0, 0);
slot.Rejects++;
long now = Now;
if (slot.LastRejectLogMs == long.MinValue || now - slot.LastRejectLogMs >= RejectLogIntervalMs)
{
slot.LastRejectLogMs = now;
log?.Invoke($"[CombatHook] {RynthAiCombat.KindNames(slot.Kind)} request {seq}: spell {spell} at 0x{target:X8} rejected ({why}); RynthAi chose instead");
}
}
private static void Consume(Slot slot, uint spellId, uint targetId, int seqAtSend = -1)
{
slot.LastSeq = slot.Request.Seq;
slot.LastSpell = spellId;
slot.LastTarget = targetId;
slot.LastAtMs = Now;
if (spellId != 0)
{
// The cast before it resolves first (its answer if one came, else none).
ObserveUseDone();
slot.Resolve(-1);
slot.PendingSeq = slot.Request.Seq;
slot.PendingSpell = spellId;
slot.PendingTarget = targetId;
slot.PendingAtMs = slot.LastAtMs;
// The count read before the send: a UseDone that lands between the send and this call is
// then still this cast's answer, not taken as the baseline.
if (seqAtSend >= 0) slot.PendingSeqAtSend = seqAtSend;
else try { slot.PendingSeqAtSend = LastUseDone?.Invoke()?.Seq ?? -1; } catch { slot.PendingSeqAtSend = -1; }
Slot? before = InFlight.Count > 0 ? InFlight[InFlight.Count - 1] : null;
if (slot.PendingSeqAtSend < 0) slot.PendingExpectSeq = -1;
else if (before != null && before.PendingExpectSeq < 0) slot.PendingExpectSeq = -1; // can't tell which answer is whose
else slot.PendingExpectSeq = Math.Max(slot.PendingSeqAtSend, before?.PendingExpectSeq ?? int.MinValue) + 1;
InFlight.Add(slot);
}
slot.Open = false;
slot.Decided = false;
}
/// <summary>One line for /ra combat.</summary>
public static string Describe()
{
long now = Now;
bool live = LeaseLive;
string head = live
? $"hook: '{Owner}' holds {RynthAiCombat.KindNames(Kinds)} (lease {Math.Max(0, LeaseUntilMs - now) / 1000.0:0.0}s)"
: "hook: none (RynthAi chooses every spell)";
static string S(Slot s) => $"{s.Opened} asked, {s.Casts} cast, {s.Declines} declined, {s.Timeouts} timed out, {s.Rejects} rejected" +
(s.Open ? $", request {s.Request.Seq} open" : "");
return $"{head} attack: {S(Attack)} heal: {S(Heal)}";
}
}
/// <summary>
/// RynthAi's side of the "RynthAi.Combat" interface: the table RynthPluginQueryInterface hands
/// out, and the functions behind it (pump thread, current plugin instance).
/// </summary>
internal static unsafe class CombatHookInterface
{
private static RynthAiCombatApiV1* _table;
public static IntPtr Query(string iface, uint version)
{
if (iface != RynthAiCombatApiV1.InterfaceName || version == 0 || version > RynthAiCombatApiV1.InterfaceVersion) return IntPtr.Zero;
if (_table == null)
{
var t = (RynthAiCombatApiV1*)NativeMemory.AllocZeroed((nuint)sizeof(RynthAiCombatApiV1));
t->Version = RynthAiCombatApiV1.InterfaceVersion;
t->StructSize = (uint)sizeof(RynthAiCombatApiV1);
t->Claim = &Claim;
t->Release = &Release;
t->Poll = &Poll;
t->Decide = &Decide;
t->GetScanned = &GetScanned;
_table = t;
}
return (IntPtr)_table;
}
/// <summary>Frees the table and drops the hook (plugin shutdown). Callers resolve it every tick.</summary>
public static void Shutdown()
{
var t = _table;
_table = null;
if (t != null) NativeMemory.Free(t);
CombatHook.Reset();
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int Claim(uint kinds, uint leaseMs, uint attackTimeoutMs, uint healTimeoutMs, byte* owner)
{
try
{
string name = owner == null ? "" : Marshal.PtrToStringUTF8((IntPtr)owner) ?? "";
return (int)CombatHook.Claim(kinds, leaseMs, attackTimeoutMs, healTimeoutMs, name);
}
catch { return 0; }
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static void Release(uint kinds)
{
try { CombatHook.Release(kinds); } catch { }
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int Poll(uint kind, CombatRequestV1* req)
{
try
{
if (req == null || !CombatHook.Poll(kind, out CombatRequestV1 r)) return 0;
uint room = req->StructSize;
uint size = (uint)sizeof(CombatRequestV1);
if (room == 0 || room > size) room = size; // an older caller passes less; never write past it
r.StructSize = room;
Buffer.MemoryCopy(&r, req, room, room);
return 1;
}
catch { return 0; }
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int Decide(uint seq, uint kind, uint spellId, uint targetId, uint flags)
{
try { return CombatHook.Decide(seq, kind, spellId, targetId, flags) ? 1 : 0; }
catch { return 0; }
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int GetScanned(uint* ids, float* distances, int capacity)
{
try { return PluginExports.Runtime.Plugin?.CombatHookScanned(ids, distances, capacity) ?? 0; }
catch { return 0; }
}
}
public sealed partial class RynthAiPlugin
{
/// <summary>RynthAi.Combat GetScanned: the combat scan list, nearest first as scanned.</summary>
internal unsafe int CombatHookScanned(uint* ids, float* distances, int capacity)
{
var list = _combatManager?.ScannedTargets;
if (list == null) return 0;
int n = list.Count;
if (ids != null)
for (int i = 0; i < n && i < capacity; i++)
{
ids[i] = unchecked((uint)list[i].Id);
if (distances != null) distances[i] = (float)list[i].Distance;
}
return n;
}
}

File diff suppressed because it is too large Load diff

View file

@ -58,10 +58,19 @@ internal static class CreatureWeakness
/// <summary>
/// The elements that hurt this monster most, or null when nothing is known. Order of
/// sources: the server table (wcid + name), then what the Damage tab learned
/// (<paramref name="learnedBest"/>) ahead of the creature-type ranking, then the type
/// ranking alone. <paramref name="creatureType"/> 0 = unknown (the name keywords decide).
/// (<paramref name="learnedBest"/>) ahead of the creature-type ranking, then the
/// UtilityBelt damage seed (<paramref name="seeded"/>, best first) ahead of the type
/// ranking, then the type ranking alone. <paramref name="creatureType"/> 0 = unknown
/// (the name keywords decide).
/// </summary>
public static Ranking? Rank(uint wcid, string? name, int creatureType, string? learnedBest)
/// <param name="seeded">
/// Damage types other players landed best on this monster (Monster Editor "Import UB
/// damage insights"), best first; null or empty = no seed. It reflects what players
/// owned as much as the monster's weakness, so it never outranks the server table or
/// this character's learned element; it only beats the generic creature-type average.
/// </param>
public static Ranking? Rank(uint wcid, string? name, int creatureType, string? learnedBest,
IReadOnlyList<string>? seeded = null)
{
EnsureLoaded();
name ??= "";
@ -86,11 +95,36 @@ internal static class CreatureWeakness
if (!e.Element.Equals(learned, StringComparison.OrdinalIgnoreCase)) r.Order.Add(e);
return r;
}
Ranking? seed = SeedRanking(seeded, type);
if (seed != null)
return seed;
if (type != null)
return new Ranking { Source = Pretty(type.Name) + " type", Order = new(type.Order) };
return null;
}
/// <summary>
/// The seed's elements (normalised, de-duplicated, no multiplier: only the order is known),
/// then the creature type's remaining elements. Null when the seed names no element.
/// </summary>
private static Ranking? SeedRanking(IReadOnlyList<string>? seeded, TypeInfo? type)
{
if (seeded == null || seeded.Count == 0) return null;
var r = new Ranking();
var seen = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
foreach (string raw in seeded)
{
string e = Normalize(raw);
if (e.Length > 0 && seen.Add(e)) r.Order.Add((e, double.NaN));
}
if (r.Order.Count == 0) return null;
r.Source = type != null ? $"UB seed, then {Pretty(type.Name)} type" : "UB seed";
if (type != null)
foreach (var e in type.Order)
if (seen.Add(e.Element)) r.Order.Add(e);
return r;
}
/// <summary>
/// The creature type the world-database table gives this monster (0 = not in it). Same match
/// as <see cref="Rank"/>: the wcid's row when its name agrees (or no name is given); no wcid,

View file

@ -0,0 +1,128 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Text.Json;
using RynthCore.CreatureSeed;
using RynthCore.Install;
namespace RynthCore.Plugin.RynthAi.CreatureData;
/// <summary>
/// Read-only view of the UtilityBelt damage-type seed (<see cref="UbMobSeedFile"/>),
/// produced by the Monster Editor's "Import UB damage insights".
/// File: <c>&lt;SuiteDir&gt;\RynthAi\CreatureData\ub-mob-seed.json</c>.
/// <para>
/// Used only as a fallback for the "Auto" damage type when a monster has no appraised
/// resists: it ranks damage types by what players actually landed on that monster, which
/// reflects what they owned as much as the monster's weakness. Never written by the plugin
/// and never fed into the per-character <see cref="MonsterDamageStore"/>.
/// </para>
/// Lookups are made from the combat thread only; the lock guards the occasional reload.
/// </summary>
internal sealed class UbMobSeedStore
{
/// <summary>Minimum time between file-change checks (the editor may rewrite the seed while playing).</summary>
private static readonly TimeSpan ReloadCheckInterval = TimeSpan.FromSeconds(15);
private readonly object _lock = new();
private readonly Dictionary<uint, UbMobSeedEntry> _byWcid = new();
private readonly Dictionary<string, UbMobSeedEntry> _byName = new(StringComparer.OrdinalIgnoreCase);
private DateTime _loadedWriteUtc = DateTime.MinValue;
private DateTime _nextCheckUtc = DateTime.MinValue;
private static string FilePath =>
Path.Combine(RynthInstallPaths.RynthAiDir, "CreatureData", UbMobSeedFile.FileName);
/// <summary>Number of seeded monsters currently loaded (wcid + name-only).</summary>
public int Count { get { lock (_lock) return _byWcid.Count + CountNameOnly(); } }
/// <summary>Loads (or reloads) the seed when the file changed. Safe to call often.</summary>
public void Load()
{
lock (_lock)
{
_nextCheckUtc = DateTime.UtcNow + ReloadCheckInterval;
string path = FilePath;
if (!File.Exists(path))
{
Clear();
return;
}
DateTime writeUtc;
try { writeUtc = File.GetLastWriteTimeUtc(path); }
catch { return; }
if (writeUtc == _loadedWriteUtc) return;
try
{
var seed = JsonSerializer.Deserialize(File.ReadAllText(path), RynthAiJsonContext.Default.UbMobSeedFile);
Clear();
_loadedWriteUtc = writeUtc;
if (seed == null || seed.Version > UbMobSeedFile.CurrentVersion) return;
foreach (var e in seed.Entries)
{
if (e.Elements == null || e.Elements.Count < 2) continue;
if (e.Wcid != 0) _byWcid[e.Wcid] = e;
IndexName(e);
}
}
catch
{
// Corrupt or mid-write file: keep whatever was loaded before and retry on the next check.
}
}
}
/// <summary>
/// Ranked damage types (best first) for a monster: exact wcid first, then name.
/// Returns false when the seed has nothing comparable for it.
/// </summary>
public bool TryGetRanked(uint wcid, string? name, out IReadOnlyList<UbMobSeedElement> ranked)
{
lock (_lock)
{
// Checked under the lock: DateTime reads are not atomic on x86. Monitor is re-entrant.
if (DateTime.UtcNow >= _nextCheckUtc) Load();
UbMobSeedEntry? entry = null;
if (wcid != 0) _byWcid.TryGetValue(wcid, out entry);
if (entry == null && !string.IsNullOrWhiteSpace(name)) _byName.TryGetValue(name.Trim(), out entry);
ranked = entry?.Elements ?? (IReadOnlyList<UbMobSeedElement>)Array.Empty<UbMobSeedElement>();
return entry != null;
}
}
/// <summary>
/// Name index: a wcid entry beats a name-only one; among equals the most-hit entry wins
/// (tier variants share a name, so the busiest variant is the best guess).
/// </summary>
private void IndexName(UbMobSeedEntry e)
{
if (string.IsNullOrWhiteSpace(e.Name)) return;
string key = e.Name.Trim();
if (_byName.TryGetValue(key, out var existing))
{
bool existingHasWcid = existing.Wcid != 0, newHasWcid = e.Wcid != 0;
if (existingHasWcid && !newHasWcid) return;
if (existingHasWcid == newHasWcid && existing.TotalHits >= e.TotalHits) return;
}
_byName[key] = e;
}
private int CountNameOnly()
{
int n = 0;
foreach (var e in _byName.Values) if (e.Wcid == 0) n++;
return n;
}
private void Clear()
{
_byWcid.Clear();
_byName.Clear();
_loadedWriteUtc = DateTime.MinValue;
}
}

View file

@ -0,0 +1,75 @@
namespace RynthCore.Plugin.RynthAi;
/// <summary>
/// One Recall On Death attempt (RynthAiPlugin.DeathRecall.cs), as a pure clock-driven state machine
/// so tests can run it. The plugin calls <see cref="Tick"/> every frame and does what it answers:
/// <see cref="Step.Fire"/> = cast the spell / use the item now. A teleport is portal space seen, or
/// the landblock changing; once one is seen nothing more is fired, and after
/// <see cref="SettleMs"/> out of portal space the run is <see cref="Step.Done"/>.
/// </summary>
internal sealed class DeathRecallRun
{
public enum Step { Wait, Fire, Done, Failed }
public const long SpellRetryMs = 4_000; // a fizzle or interrupted cast: try again
public const long ItemRetryMs = 6_000; // a gem's use animation takes ~3 s before the portal
public const int MaxFires = 5;
public const long TimeoutMs = 60_000;
public const long SettleMs = 3_000; // out of portal space this long before nav/corpse travel
private readonly long _retryMs;
private readonly long _startedAt;
private readonly uint _startLandblock;
private long _lastFireAt;
private long _teleportedAt;
private bool _sawPortal;
public int Fires { get; private set; }
public string FailReason { get; private set; } = string.Empty;
public bool Teleported => _teleportedAt != 0 || _sawPortal;
/// <param name="useItem">True for a gem or other item (slower retry), false for a spell.</param>
/// <param name="now">Clock in ms.</param>
/// <param name="startLandblock">Landblock (cell &gt;&gt; 16) at the start; 0 when unknown.</param>
public DeathRecallRun(bool useItem, long now, uint startLandblock)
{
_retryMs = useItem ? ItemRetryMs : SpellRetryMs;
_startedAt = now;
_startLandblock = startLandblock;
}
/// <param name="now">Clock in ms.</param>
/// <param name="inPortalSpace">The client is in portal space.</param>
/// <param name="landblock">Current landblock; 0 when unknown.</param>
/// <param name="ready">Ready to fire (a spell: wand wielded and in magic mode).</param>
public Step Tick(long now, bool inPortalSpace, uint landblock, bool ready)
{
if (inPortalSpace) { _sawPortal = true; return Step.Wait; }
bool moved = landblock != 0 && _startLandblock != 0 && landblock != _startLandblock;
if (_sawPortal || moved)
{
if (_teleportedAt == 0) _teleportedAt = now;
return now - _teleportedAt >= SettleMs ? Step.Done : Step.Wait;
}
if (now - _startedAt > TimeoutMs)
return Fail($"no teleport within {TimeoutMs / 1000} s");
if (Fires >= MaxFires && now - _lastFireAt >= _retryMs)
return Fail($"no teleport after {MaxFires} tries");
if (!ready || Fires >= MaxFires)
return Step.Wait;
if (Fires > 0 && now - _lastFireAt < _retryMs)
return Step.Wait;
Fires++;
_lastFireAt = now;
return Step.Fire;
}
private Step Fail(string why)
{
FailReason = why;
return Step.Failed;
}
}

View file

@ -0,0 +1,321 @@
using System;
using System.Collections.Generic;
using System.IO;
namespace RynthCore.Plugin.RynthAi.Diagnostics;
/// <summary>Why a write in RynthAi's data folders failed (see <see cref="DataWriteGuard.Classify"/>).</summary>
internal enum WriteFailureKind
{
/// <summary>Windows refused: the folder or file isn't writable for this account, or Controlled folder access blocked acclient.exe.</summary>
AccessDenied,
/// <summary>The file carries the ReadOnly attribute and it couldn't be cleared.</summary>
ReadOnlyFile,
/// <summary>Another program holds the file open (editor, sync client, antivirus).</summary>
InUse,
DiskFull,
/// <summary>A OneDrive (cloud files) placeholder whose sync provider isn't running.</summary>
CloudProvider,
/// <summary>The folder doesn't exist and couldn't be created.</summary>
PathMissing,
Other,
}
/// <summary>
/// Saves of metas, navs, loot profiles and settings profiles (2026-10-13). Players reported
/// that metas and navs "don't save" and that "the plugin folders are read only": every one of
/// those saves swallowed its exception, so a folder the client can't write looked like a save
/// that silently did nothing. Now:
/// - <see cref="PrepareOverwrite"/> clears the ReadOnly attribute on our own file before it
/// is overwritten (works whenever the folder itself is writable);
/// - <see cref="Report"/> says in chat, once per folder per session, what couldn't be saved,
/// where and why (access denied / read-only file / file in use / ...), with the fix (the
/// launcher's Recovery Actions > Fix folder permissions). Every failure is logged
/// (throttled per folder so a failing autosave can't flood the log);
/// - <see cref="CheckFolders"/> is the startup self-check: it tries to create a file in
/// each data folder.
/// Chat lines are queued here and posted by the plugin tick once the character is in game
/// (<see cref="DrainChat"/>), so a failure on any thread, or before login, still shows.
/// </summary>
internal static class DataWriteGuard
{
public const string FixHint =
"Fix: in the RynthCore launcher, Recovery Actions > Fix folder permissions (one administrator prompt).";
/// <summary>A failing folder logs at most once per this many ms (plus a count of the skipped ones).</summary>
public const long LogThrottleMs = 60_000;
private static readonly object Gate = new();
private static readonly HashSet<string> ReportedFolders = new(StringComparer.OrdinalIgnoreCase);
private static readonly Dictionary<string, (long At, int Skipped)> LastLog = new(StringComparer.OrdinalIgnoreCase);
private static readonly Queue<string> PendingChat = new();
/// <summary>The plugin's log (Initialize sets it). Null: nothing is logged.</summary>
public static Action<string>? LogSink;
/// <summary>Milliseconds clock; tests replace it.</summary>
internal static Func<long> Clock = () => Environment.TickCount64;
/// <summary>Forgets what was reported (a new session; tests).</summary>
public static void Reset()
{
lock (Gate)
{
ReportedFolders.Clear();
LastLog.Clear();
PendingChat.Clear();
}
}
/// <summary>Chat lines waiting to be posted.</summary>
public static int PendingCount { get { lock (Gate) return PendingChat.Count; } }
/// <summary>Posts the queued chat lines (plugin tick, in game).</summary>
public static void DrainChat(Action<string> chat)
{
while (true)
{
string line;
lock (Gate)
{
if (PendingChat.Count == 0) return;
line = PendingChat.Dequeue();
}
try { chat(line); } catch { }
}
}
/// <summary>
/// Clears the ReadOnly attribute of an existing file we are about to overwrite. Returns
/// true when it was set and is now cleared. Never throws: when the folder isn't writable
/// either, the write that follows fails and is reported.
/// </summary>
public static bool PrepareOverwrite(string path)
{
try
{
if (string.IsNullOrEmpty(path) || !File.Exists(path)) return false;
FileAttributes a = File.GetAttributes(path);
if ((a & FileAttributes.ReadOnly) == 0) return false;
File.SetAttributes(path, a & ~FileAttributes.ReadOnly);
Log($"[RynthAi] {path} was marked read-only; cleared that so it can be saved.");
return true;
}
catch
{
return false;
}
}
/// <summary>
/// Runs <paramref name="write"/> for <paramref name="path"/> (ReadOnly cleared first).
/// False when it threw; the failure is then reported (<see cref="Report"/>).
/// </summary>
public static bool TrySave(string what, string path, Action write) => TrySave(what, path, write, out _);
/// <inheritdoc cref="TrySave(string, string, Action)"/>
/// <param name="reason">When it failed, the reason and the fix in plain words ("access denied (...). Fix: ..."), else empty.</param>
/// <param name="callerShows">The caller puts the failure in chat itself (an explicit save the
/// player asked for): nothing is queued, the folder still counts as reported.</param>
public static bool TrySave(string what, string path, Action write, out string reason, bool callerShows = false)
{
reason = string.Empty;
try
{
PrepareOverwrite(path);
write();
return true;
}
catch (Exception ex)
{
reason = Report(what, path, ex, callerShows);
return false;
}
}
// ERROR_* as HRESULTs (0x8007xxxx).
private const int HrAccessDenied = unchecked((int)0x80070005);
private const int HrWriteProtect = unchecked((int)0x80070013);
private const int HrSharingViolation = unchecked((int)0x80070020);
private const int HrLockViolation = unchecked((int)0x80070021);
private const int HrHandleDiskFull = unchecked((int)0x80070027);
private const int HrDiskFull = unchecked((int)0x80070070);
private const int HrCloudProviderNotRunning = unchecked((int)0x8007016A);
private const int HrCloudNotInSync = unchecked((int)0x80070185);
private const int HrUserMappedFile = unchecked((int)0x800704C8);
/// <summary>What kind of failure <paramref name="ex"/> is, for a write of <paramref name="path"/>.</summary>
public static WriteFailureKind Classify(Exception ex, string? path)
{
switch (ex)
{
case UnauthorizedAccessException:
return IsReadOnlyFile(path) ? WriteFailureKind.ReadOnlyFile : WriteFailureKind.AccessDenied;
case DirectoryNotFoundException:
return WriteFailureKind.PathMissing;
case IOException io:
switch (io.HResult)
{
case HrSharingViolation:
case HrLockViolation:
case HrUserMappedFile:
return WriteFailureKind.InUse;
case HrDiskFull:
case HrHandleDiskFull:
return WriteFailureKind.DiskFull;
case HrCloudProviderNotRunning:
case HrCloudNotInSync:
return WriteFailureKind.CloudProvider;
case HrAccessDenied:
case HrWriteProtect:
return IsReadOnlyFile(path) ? WriteFailureKind.ReadOnlyFile : WriteFailureKind.AccessDenied;
}
return WriteFailureKind.Other;
default:
return WriteFailureKind.Other;
}
}
private static bool IsReadOnlyFile(string? path)
{
try
{
return !string.IsNullOrEmpty(path) && File.Exists(path)
&& (File.GetAttributes(path) & FileAttributes.ReadOnly) != 0;
}
catch { return false; }
}
/// <summary>The reason in plain words.</summary>
public static string Describe(WriteFailureKind kind, Exception? ex) => kind switch
{
WriteFailureKind.AccessDenied =>
"access denied (Windows doesn't let this game client write there: the folder's permissions, " +
"or Windows Security's Controlled folder access blocking acclient.exe)",
WriteFailureKind.ReadOnlyFile => "the file is marked read-only and RynthAi couldn't clear that",
WriteFailureKind.InUse => "the file is open in another program (an editor, OneDrive or backup sync, antivirus)",
WriteFailureKind.DiskFull => "the disk is full",
WriteFailureKind.CloudProvider => "the folder is synced by OneDrive (or another cloud app) that isn't running",
WriteFailureKind.PathMissing => "the folder doesn't exist and couldn't be created",
_ => ex?.Message ?? "unknown error",
};
/// <summary>What the player can do about it.</summary>
public static string Hint(WriteFailureKind kind) => kind switch
{
WriteFailureKind.AccessDenied or WriteFailureKind.ReadOnlyFile or WriteFailureKind.PathMissing => FixHint,
WriteFailureKind.InUse => "Close the program that has it open and save again.",
WriteFailureKind.DiskFull => "Free some disk space and save again.",
WriteFailureKind.CloudProvider => "Start OneDrive, or install RynthSuite outside the synced folder.",
_ => FixHint,
};
/// <summary>
/// A failed save of <paramref name="what"/> ("the meta", "the nav", ...) to
/// <paramref name="path"/>: logged (throttled per folder) and, the first time for that
/// folder this session, queued for chat. Returns the reason and the fix in plain words.
/// </summary>
public static string Report(string what, string path, Exception ex, bool callerShows = false)
{
WriteFailureKind kind = Classify(ex, path);
string reason = Describe(kind, ex);
string folder = FolderOf(path);
bool chat;
string? logLine = null;
lock (Gate)
{
chat = !AlreadyReported(folder);
ReportedFolders.Add(folder);
long now = Clock();
if (!LastLog.TryGetValue(folder, out var last) || now - last.At >= LogThrottleMs || chat)
{
string skipped = last.Skipped > 0 ? $" ({last.Skipped} more failure(s) in this folder since the last line)" : "";
logLine = $"[RynthAi] Save failed: {what} -> {path}: {reason} [{ex.GetType().Name}: {ex.Message}]{skipped}";
LastLog[folder] = (now, 0);
}
else
{
LastLog[folder] = (last.At, last.Skipped + 1);
}
if (chat && !callerShows)
PendingChat.Enqueue($"[RynthAi] Couldn't save {what} to {path}: {reason}. {Hint(kind)} " +
"(Shown once per folder; later failures there go to the log.)");
}
if (logLine != null) Log(logLine);
return $"{reason}. {Hint(kind)}";
}
/// <summary>One data folder the self-check couldn't write.</summary>
internal readonly record struct FolderProblem(string Folder, WriteFailureKind Kind, string Reason);
/// <summary>
/// The startup self-check: creates (if missing) and writes a throw-away file in each of
/// <paramref name="folders"/>. Returns the folders that failed; for those, one line goes
/// to the log and one summary line is queued for chat.
/// </summary>
public static List<FolderProblem> CheckFolders(IEnumerable<string> folders)
{
var problems = new List<FolderProblem>();
foreach (string folder in folders)
{
if (string.IsNullOrEmpty(folder)) continue;
string probe = Path.Combine(folder, $".rynthai-write-check-{Environment.ProcessId}-{Guid.NewGuid():N}.tmp");
try
{
Directory.CreateDirectory(folder);
using (var fs = new FileStream(probe, FileMode.CreateNew, FileAccess.Write, FileShare.None, 1, FileOptions.DeleteOnClose))
fs.WriteByte(0);
}
catch (Exception ex)
{
WriteFailureKind kind = Classify(ex, null);
problems.Add(new FolderProblem(folder, kind, Describe(kind, ex)));
Log($"[RynthAi] Data folder not writable: {folder}: {Describe(kind, ex)} [{ex.GetType().Name}: {ex.Message}]");
}
finally
{
try { if (File.Exists(probe)) File.Delete(probe); } catch { }
}
}
if (problems.Count > 0)
{
lock (Gate)
{
foreach (var p in problems) ReportedFolders.Add(p.Folder); // the save itself needn't repeat it
string list = problems.Count == 1
? problems[0].Folder
: $"{problems.Count} folders ({string.Join(", ", problems.ConvertAll(p => Path.GetFileName(p.Folder)))})";
PendingChat.Enqueue($"[RynthAi] Can't write to {list}: {problems[0].Reason}. Metas, navs, loot and settings " +
$"saved there will NOT be kept. {Hint(problems[0].Kind)}");
}
}
return problems;
}
/// <summary>This folder, or one it is inside (e.g. SettingsProfiles for a character's folder), was reported. Under Gate.</summary>
private static bool AlreadyReported(string folder)
{
foreach (string f in ReportedFolders)
if (folder.Equals(f, StringComparison.OrdinalIgnoreCase)
|| folder.StartsWith(f + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase))
return true;
return false;
}
/// <summary>The folder a failure is counted against.</summary>
internal static string FolderOf(string path)
{
try
{
string? dir = Path.GetDirectoryName(path);
return string.IsNullOrEmpty(dir) ? path : dir.TrimEnd('\\', '/');
}
catch { return path; }
}
private static void Log(string line)
{
try { LogSink?.Invoke(line); } catch { }
}
}

File diff suppressed because it is too large Load diff

View file

@ -2,6 +2,7 @@ using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using RynthCore.Install;
namespace RynthCore.Plugin.RynthAi;

View file

@ -30,6 +30,7 @@ using System.Collections.Generic;
using System.Globalization;
using System.IO;
using RynthCore.Plugin.RynthAi.Raycasting;
using RynthCore.Install;
namespace RynthCore.Plugin.RynthAi;

View file

@ -55,7 +55,9 @@ internal static partial class DungeonPathfinder
// castles most approach/exit points in short bend and junction cells sat on the bend's
// outer wall (Rithwic Crypt: 440 of 488 under 0.25 m), and a dead end's look-in point is
// its cell origin, which is inside the end cap.
internal const double WallClearance = 1.0;
// The patrol's is a setting (DungeonPatrolOptions.WallClearance, Settings "Distance From
// Walls"); this default is what dunnav paths and recovery detours always use.
internal const double WallClearance = DungeonPatrolOptions.WallClearanceDefault;
// How far a point may be pushed off where its rule put it to get that clearance.
private const double DoorwayPushMax = 2.0, CornerPushMax = 1.5, MiddlePushMax = 4.5;
@ -176,7 +178,7 @@ internal static partial class DungeonPathfinder
/// </summary>
private static NavRouteParser? BuildRoomPatrol(
Dictionary<uint, DungeonNavNode> graph, uint startCell, HashSet<uint> mainRoute,
IReadOnlySet<uint>? hazardCells, DungeonGeometry geo)
IReadOnlySet<uint>? hazardCells, DungeonGeometry geo, DungeonPatrolOptions o)
{
var rooms = BuildRooms(graph, geo, hazardCells);
var patrolRooms = new HashSet<int>();
@ -255,7 +257,7 @@ internal static partial class DungeonPathfinder
var steps = new List<Step>(walk.Count);
foreach (var e in walk) steps.Add(new Step(e.From, e.To, e.Key));
var route = new NavRouteParser { RouteType = NavRouteType.Circular };
route.Points.AddRange(EmitSteps(graph, geo, rooms, steps, closed: true, null, 0, null, 0, out _));
route.Points.AddRange(EmitSteps(graph, geo, rooms, steps, closed: true, null, 0, null, 0, o, out _));
return route;
}
@ -333,7 +335,8 @@ internal static partial class DungeonPathfinder
if (cellPath.Count == 0) return pts;
var start = WorldPoint(DungeonGeometry.NavToWorld(startEW), DungeonGeometry.NavToWorld(startNS), startZ, false);
var dest = WorldPoint(DungeonGeometry.NavToWorld(destEW), DungeonGeometry.NavToWorld(destNS), destZ, false);
return EmitSteps(graph, geo, rooms, steps, closed: false, start, cellPath[0], dest, cellPath[cellPath.Count - 1], out doorways);
return EmitSteps(graph, geo, rooms, steps, closed: false, start, cellPath[0], dest, cellPath[cellPath.Count - 1],
DungeonPatrolOptions.Default, out doorways);
}
// ── Laying points along doorway steps ────────────────────────────────────
@ -353,15 +356,16 @@ internal static partial class DungeonPathfinder
/// </summary>
private static List<NavPoint> EmitSteps(
Dictionary<uint, DungeonNavNode> graph, DungeonGeometry geo, DungeonRooms rooms, List<Step> steps, bool closed,
NavPoint? start, uint startCell, NavPoint? dest, uint destCell, out int doorways)
NavPoint? start, uint startCell, NavPoint? dest, uint destCell, DungeonPatrolOptions o, out int doorways)
{
doorways = 0;
var pts = new List<NavPoint>();
double wall = o.WallClearance;
if (steps.Count == 0)
{
if (start != null && dest != null && rooms.RoomOf.TryGetValue(startCell, out int r0))
CrossRoom(pts, graph, geo, rooms, r0, start, startCell, dest, destCell, revisit: false);
CrossRoom(pts, graph, geo, rooms, r0, start, startCell, dest, destCell, revisit: false, wall);
return pts;
}
@ -383,14 +387,14 @@ internal static partial class DungeonPathfinder
int j = i;
while (j + 1 < steps.Count && Continues(geo, steps[j], steps[j + 1])) j++;
RunPoints(graph, geo, rooms, steps, i, j, out var approach, out var middle, out var exit, out bool narrow);
RunPoints(graph, geo, rooms, steps, i, j, wall, out var approach, out var middle, out var exit, out bool narrow);
if (narrow) doorways++;
if (prev != null)
{
// Only the patrol looks into rooms; a path to somewhere (dunnav, a detour) doesn't.
string? why = null;
bool revisit = i > 0 && (closed ? LooksIn(graph, rooms, lookedInto, steps[i - 1], steps[i], prev, approach, out why) : steps[i - 1].Key == steps[i].Key);
CrossRoom(pts, graph, geo, rooms, rooms.RoomOf[steps[i].From], prev, prevCell, approach, steps[i].From, revisit, why);
bool revisit = i > 0 && (closed ? LooksIn(graph, rooms, lookedInto, steps[i - 1], steps[i], prev, approach, o.LookInRoomMeters, out why) : steps[i - 1].Key == steps[i].Key);
CrossRoom(pts, graph, geo, rooms, rooms.RoomOf[steps[i].From], prev, prevCell, approach, steps[i].From, revisit, wall, why);
}
else firstApproach = approach;
Append(pts, approach);
@ -403,14 +407,14 @@ internal static partial class DungeonPathfinder
if (closed && firstApproach != null && prev != null)
{
bool revisit = LooksIn(graph, rooms, lookedInto, steps[steps.Count - 1], steps[0], prev, firstApproach, out string why);
CrossRoom(pts, graph, geo, rooms, rooms.RoomOf[steps[0].From], prev, prevCell, firstApproach, steps[0].From, revisit, why);
bool revisit = LooksIn(graph, rooms, lookedInto, steps[steps.Count - 1], steps[0], prev, firstApproach, o.LookInRoomMeters, out string why);
CrossRoom(pts, graph, geo, rooms, rooms.RoomOf[steps[0].From], prev, prevCell, firstApproach, steps[0].From, revisit, wall, why);
}
if (!closed && dest != null && prev != null && rooms.RoomOf.TryGetValue(destCell, out int rd))
CrossRoom(pts, graph, geo, rooms, rd, prev, prevCell, dest, destCell, revisit: false);
CrossRoom(pts, graph, geo, rooms, rd, prev, prevCell, dest, destCell, revisit: false, wall);
DropCollinear(pts, closed);
KeepLegsOffWalls(geo, pts, closed);
KeepLegsOffWalls(geo, pts, closed, wall);
return pts;
}
@ -426,19 +430,19 @@ internal static partial class DungeonPathfinder
/// across a corner), a corner is put in: the leg's tightest spot, pushed off the wall,
/// kept only when both new legs are clearer than the old one.
/// </summary>
internal static void KeepLegsOffWalls(DungeonGeometry geo, List<NavPoint> pts, bool closed)
internal static void KeepLegsOffWalls(DungeonGeometry geo, List<NavPoint> pts, bool closed, double wall = WallClearance)
{
int budget = pts.Count / 2 + 8, perLeg = 0;
int i = 0;
while (i < (closed ? pts.Count : pts.Count - 1) && pts.Count >= 2)
{
var a = pts[i]; var b = pts[(i + 1) % pts.Count];
double least = LegLeast(geo, a, b, out double wx, out double wy, out double wz);
double target = Math.Min(LegMinClearance, Math.Min(PointClearance(geo, a), PointClearance(geo, b)));
double least = LegLeast(geo, a, b, wall, out double wx, out double wy, out double wz);
double target = Math.Min(Math.Min(LegMinClearance, wall), Math.Min(PointClearance(geo, a, wall), PointClearance(geo, b, wall)));
if (least >= target - 0.05 || budget <= 0 || perLeg >= 3) { i++; perLeg = 0; continue; }
// The corner leaving both new legs clearest, if that is clearly better.
NavPoint? best = BestCorner(geo, a, b, wx, wy, wz, least + 0.1, out _);
NavPoint? best = BestCorner(geo, a, b, wx, wy, wz, least + 0.1, wall, out _);
if (best != null)
{
pts.Insert(i + 1, Tag(best, "leg-corner"));
@ -448,11 +452,11 @@ internal static partial class DungeonPathfinder
// No one corner does it (a jog round two corners): a first corner the walk reaches
// clear, then the best corner for the rest.
bool two = false;
foreach (var first in CornerCandidates(geo, wx, wy, wz))
foreach (var first in CornerCandidates(geo, wx, wy, wz, wall))
{
if (LegLeast(geo, a, first, out _, out _, out _) < target - 0.05 || TurnsBack(a, first, b)) continue;
double rest = LegLeast(geo, first, b, out double rx, out double ry, out double rz);
var second = BestCorner(geo, first, b, rx, ry, rz, Math.Max(rest, least) + 0.1, out double m2);
if (LegLeast(geo, a, first, wall, out _, out _, out _) < target - 0.05 || TurnsBack(a, first, b)) continue;
double rest = LegLeast(geo, first, b, wall, out double rx, out double ry, out double rz);
var second = BestCorner(geo, first, b, rx, ry, rz, Math.Max(rest, least) + 0.1, wall, out double m2);
if (second == null || m2 <= least + 0.1) continue;
pts.Insert(i + 1, Tag(first, "leg-corner"));
pts.Insert(i + 2, Tag(second, "leg-corner"));
@ -468,10 +472,10 @@ internal static partial class DungeonPathfinder
// Corners to try for a leg whose tightest spot is (wx, wy, wz): that spot pushed off the
// wall, and the centres of the openings near it (a leg that jogs through the wrong side of a
// junction needs the opening it skipped).
private static List<NavPoint> CornerCandidates(DungeonGeometry geo, double wx, double wy, double wz)
private static List<NavPoint> CornerCandidates(DungeonGeometry geo, double wx, double wy, double wz, double wall)
{
double cx = wx, cy = wy;
geo.PushClear(ref cx, ref cy, wz, WallClearance, LegCornerPushMax);
geo.PushClear(ref cx, ref cy, wz, wall, LegCornerPushMax);
var list = new List<NavPoint> { WorldPoint(cx, cy, wz, false) };
foreach (var d in geo.DoorwaysNear(wx, wy, wz, LegCornerSearch)) list.Add(WorldPoint(d.X, d.Y, d.Z, false));
return list;
@ -479,15 +483,15 @@ internal static partial class DungeonPathfinder
// The candidate leaving both new legs a-corner-b clearest, if better than mustBeat.
private static NavPoint? BestCorner(DungeonGeometry geo, NavPoint a, NavPoint b, double wx, double wy, double wz,
double mustBeat, out double bestMin)
double mustBeat, double wall, out double bestMin)
{
NavPoint? best = null;
bestMin = mustBeat;
foreach (var corner in CornerCandidates(geo, wx, wy, wz))
foreach (var corner in CornerCandidates(geo, wx, wy, wz, wall))
{
if (PointClearance(geo, corner) <= mustBeat) continue;
if (PointClearance(geo, corner, wall) <= mustBeat) continue;
if (TurnsBack(a, corner, b)) continue;
double m = Math.Min(LegLeast(geo, a, corner, out _, out _, out _), LegLeast(geo, corner, b, out _, out _, out _));
double m = Math.Min(LegLeast(geo, a, corner, wall, out _, out _, out _), LegLeast(geo, corner, b, wall, out _, out _, out _));
if (m > bestMin) { bestMin = m; best = corner; }
}
return best;
@ -504,30 +508,30 @@ internal static partial class DungeonPathfinder
return (ux * vx + uy * vy) / (lu * lv) < Math.Cos(120.0 * Math.PI / 180.0);
}
private static double LegLeast(DungeonGeometry geo, NavPoint a, NavPoint b, out double wx, out double wy, out double wz)
private static double LegLeast(DungeonGeometry geo, NavPoint a, NavPoint b, double wall, out double wx, out double wy, out double wz)
=> geo.LegClearance(DungeonGeometry.NavToWorld(a.EW), DungeonGeometry.NavToWorld(a.NS), a.Z * 240.0,
DungeonGeometry.NavToWorld(b.EW), DungeonGeometry.NavToWorld(b.NS), b.Z * 240.0,
WallClearance, LegEndSkip, out wx, out wy, out wz);
wall, LegEndSkip, out wx, out wy, out wz);
private static double PointClearance(DungeonGeometry geo, NavPoint p)
=> geo.ClearanceMemo(DungeonGeometry.NavToWorld(p.EW), DungeonGeometry.NavToWorld(p.NS), p.Z * 240.0, WallClearance + 0.5);
private static double PointClearance(DungeonGeometry geo, NavPoint p, double wall)
=> geo.ClearanceMemo(DungeonGeometry.NavToWorld(p.EW), DungeonGeometry.NavToWorld(p.NS), p.Z * 240.0, wall + 0.5);
// A big room (its cells spread over 10 m or more) left again close to where it was entered is looked into: a
// A big room (its cells spread over 10 m or more by default: DungeonPatrolOptions.LookInRoomMeters,
// Settings "Walk Into Rooms From") left again close to where it was entered is looked into: a
// walk to its middle and back. A straight crossing to a nearby opening would only skirt
// it (the patrol hunts; the old cell walk went all round such rooms). Also any room left
// by the opening it was entered by.
private const double LookInMinSpreadMeters = 10.0;
private const double LookInMaxSkirtMeters = 8.0;
// Once per room per lap: a hub room with many doorways was otherwise walked to its middle
// again every time the patrol passed between two of its doorways.
private static bool LooksIn(Dictionary<uint, DungeonNavNode> graph, DungeonRooms rooms, HashSet<int> lookedInto,
Step inStep, Step outStep, NavPoint entered, NavPoint leaving, out string why)
Step inStep, Step outStep, NavPoint entered, NavPoint leaving, double lookInMeters, out string why)
{
why = "cross";
if (!rooms.RoomOf.TryGetValue(outStep.From, out int r)) return false;
double spread = RoomSpreadMeters(graph, rooms.Cells[r]);
bool big = spread >= LookInMinSpreadMeters;
bool big = spread >= lookInMeters;
bool sameDoor = inStep.Key == outStep.Key;
double skirt = NavPointYd(entered, leaving);
bool look = (sameDoor && (big || rooms.Cells[r].Count == 1))
@ -548,7 +552,7 @@ internal static partial class DungeonPathfinder
// The diagonal of the box round a room's cell origins: 0 for the pieces of one junction
// (several cells, one origin), 28 m for a 3x3 room of 10 m cells.
private static double RoomSpreadMeters(Dictionary<uint, DungeonNavNode> graph, List<uint> cells)
internal static double RoomSpreadMeters(Dictionary<uint, DungeonNavNode> graph, List<uint> cells)
{
double minN = double.MaxValue, maxN = double.MinValue, minE = double.MaxValue, maxE = double.MinValue;
foreach (uint c in cells)
@ -582,18 +586,18 @@ internal static partial class DungeonPathfinder
// The approach point before steps[i], the exit point after steps[j], and the opening centres
// between them when the run turns (more than 25 degrees between openings).
private static void RunPoints(Dictionary<uint, DungeonNavNode> graph, DungeonGeometry geo, DungeonRooms rooms,
List<Step> steps, int i, int j,
List<Step> steps, int i, int j, double wall,
out NavPoint approach, out List<NavPoint> middle, out NavPoint exit, out bool narrow)
{
middle = new List<NavPoint>();
if (i == j)
{
if (!DoorwayPoints(graph, geo, rooms, steps[i].From, steps[i].To, out approach, out exit, out narrow)) narrow = false;
if (!DoorwayPoints(graph, geo, rooms, steps[i].From, steps[i].To, wall, out approach, out exit, out narrow)) narrow = false;
return;
}
DoorwayPoints(graph, geo, rooms, steps[i].From, steps[i].To, out approach, out _, out bool n0);
DoorwayPoints(graph, geo, rooms, steps[j].From, steps[j].To, out _, out exit, out bool n1);
DoorwayPoints(graph, geo, rooms, steps[i].From, steps[i].To, wall, out approach, out _, out bool n0);
DoorwayPoints(graph, geo, rooms, steps[j].From, steps[j].To, wall, out _, out exit, out bool n1);
narrow = n0 || n1;
var doors = new List<(DungeonDoorway Door, uint From, int Step)>();
for (int k = i; k <= j; k++)
@ -621,7 +625,7 @@ internal static partial class DungeonPathfinder
var m = Note(Tag(WorldPoint(d.X, d.Y, d.Z, !d.IsWide), "run-opening"), steps[k].From, steps[k].From, steps[k].To, "doorway-run");
if (prevM != null && k == prevStep + 1
&& rooms.RoomOf.TryGetValue(steps[prevStep].To, out int ra) && rooms.RoomOf.TryGetValue(steps[k].From, out int rb) && ra == rb)
PullThrough(middle, graph, geo, rooms, rooms.Cells[ra], prevM, steps[prevStep].To, m, steps[k].From);
PullThrough(middle, graph, geo, rooms, rooms.Cells[ra], prevM, steps[prevStep].To, m, steps[k].From, wall);
Append(middle, m);
prevM = m;
prevStep = k;
@ -639,15 +643,15 @@ internal static partial class DungeonPathfinder
/// NavPoint.Doorway). Unknown openings fall back to the old 30% / 50% points.
/// </summary>
private static bool DoorwayPoints(Dictionary<uint, DungeonNavNode> graph, DungeonGeometry geo, DungeonRooms rooms,
uint a, uint b, out NavPoint approach, out NavPoint exit, out bool narrow)
uint a, uint b, double wall, out NavPoint approach, out NavPoint exit, out bool narrow)
{
narrow = false;
if (geo.TryGetDoorway(a, b, out var d))
{
var (nx, ny) = d.NormalFrom(a);
narrow = !d.IsWide;
approach = Note(Tag(DoorwayPoint(geo, rooms, a, d, -nx, -ny, narrow), "approach"), a, a, b, "doorway");
exit = Note(Tag(DoorwayPoint(geo, rooms, b, d, nx, ny, narrow), "exit"), b, a, b, "doorway");
approach = Note(Tag(DoorwayPoint(geo, rooms, a, d, -nx, -ny, narrow, wall), "approach"), a, a, b, "doorway");
exit = Note(Tag(DoorwayPoint(geo, rooms, b, d, nx, ny, narrow, wall), "exit"), b, a, b, "doorway");
return true;
}
@ -656,8 +660,8 @@ internal static partial class DungeonPathfinder
approach = Tag(new NavPoint { Type = NavPointType.Point, NS = na.NS + dNS * 0.3, EW = na.EW + dEW * 0.3, Z = (na.Z + dZ * 0.3) / 240.0 }, "cell-fallback");
exit = Tag(new NavPoint { Type = NavPointType.Point, NS = na.NS + dNS * 0.5, EW = na.EW + dEW * 0.5, Z = (na.Z + dZ * 0.5) / 240.0 }, "cell-fallback");
Note(approach, a, a, b, "doorway(no-opening)"); Note(exit, 0, a, b, "doorway(no-opening)");
PushOffWalls(geo, approach, RoomCells(rooms, a), CornerPushMax);
PushOffWalls(geo, exit, null, CornerPushMax); // on the line between the two rooms
PushOffWalls(geo, approach, RoomCells(rooms, a), CornerPushMax, wall);
PushOffWalls(geo, exit, null, CornerPushMax, wall); // on the line between the two rooms
return false;
}
@ -669,12 +673,12 @@ internal static partial class DungeonPathfinder
/// (in a corridor too narrow for the clearance, onto its middle).
/// </summary>
private static NavPoint DoorwayPoint(DungeonGeometry geo, DungeonRooms rooms, uint cell, DungeonDoorway d,
double dirX, double dirY, bool narrow)
double dirX, double dirY, bool narrow, double wall)
{
var cells = RoomCells(rooms, cell);
double s = PickStandoff(geo, cells, d, dirX, dirY, out double clearance);
double s = PickStandoff(geo, cells, d, dirX, dirY, out double clearance, wall);
var p = WorldPoint(d.X + dirX * s, d.Y + dirY * s, d.Z, narrow);
if (clearance < WallClearance) PushOffWalls(geo, p, cells, DoorwayPushMax);
if (clearance < wall) PushOffWalls(geo, p, cells, DoorwayPushMax, wall);
return p;
}
@ -684,7 +688,7 @@ internal static partial class DungeonPathfinder
// The longest standoff whose point is on the floor of the cell's room with WallClearance;
// else the one with the most clearance (the longer of near ties); else the shortest.
internal static double PickStandoff(DungeonGeometry geo, IReadOnlyCollection<uint> cells, DungeonDoorway d,
double dirX, double dirY, out double clearance)
double dirX, double dirY, out double clearance, double wall = WallClearance)
{
double bestS = -1;
clearance = 0;
@ -692,20 +696,21 @@ internal static partial class DungeonPathfinder
{
double px = d.X + dirX * s, py = d.Y + dirY * s;
if (!geo.OnFloorOfAny(cells, px, py, d.Z)) continue;
double c = geo.ClearanceMemo(px, py, d.Z, WallClearance + 0.5);
if (c >= WallClearance) { clearance = c; return s; }
double c = geo.ClearanceMemo(px, py, d.Z, wall + 0.5);
if (c >= wall) { clearance = c; return s; }
if (bestS < 0 || c > clearance + 0.05) { bestS = s; clearance = c; }
}
return bestS > 0 ? bestS : DoorwayStandoffShortest;
}
/// <summary>Moves a point (in place) to WallClearance from walls and floor edges, at most
/// <paramref name="maxMove"/>, staying on the floor of <paramref name="cells"/> when given.</summary>
private static void PushOffWalls(DungeonGeometry geo, NavPoint p, IReadOnlyCollection<uint>? cells, double maxMove)
/// <summary>Moves a point (in place) to <paramref name="wall"/> (the patrol's wall distance,
/// WallClearance by default) from walls and floor edges, at most <paramref name="maxMove"/>,
/// staying on the floor of <paramref name="cells"/> when given.</summary>
private static void PushOffWalls(DungeonGeometry geo, NavPoint p, IReadOnlyCollection<uint>? cells, double maxMove, double wall)
{
double x = DungeonGeometry.NavToWorld(p.EW), y = DungeonGeometry.NavToWorld(p.NS);
double ox = x, oy = y;
geo.PushClear(ref x, ref y, p.Z * 240.0, WallClearance, maxMove, cells);
geo.PushClear(ref x, ref y, p.Z * 240.0, wall, maxMove, cells);
if (x == ox && y == oy) return;
p.EW = DungeonGeometry.WorldToNav(x);
p.NS = DungeonGeometry.WorldToNav(y);
@ -721,26 +726,26 @@ internal static partial class DungeonPathfinder
/// </summary>
private static void CrossRoom(List<NavPoint> pts, Dictionary<uint, DungeonNavNode> graph, DungeonGeometry geo,
DungeonRooms rooms, int room, NavPoint from, uint fromCell, NavPoint to, uint toCell,
bool revisit, string? why = null)
bool revisit, double wall, string? why = null)
{
var cells = rooms.Cells[room];
Trace?.Invoke($"cross room {room} ({cells.Count}) revisit={revisit} from={fromCell:X8} to={toCell:X8}");
if (revisit)
{
var mid = RoomMiddle(graph, geo, cells, out uint midCell);
var mid = RoomMiddle(graph, geo, cells, wall, out uint midCell);
if (mid != null)
{
int before = pts.Count;
Note(mid, midCell);
PullThrough(pts, graph, geo, rooms, cells, from, fromCell, mid, midCell);
PullThrough(pts, graph, geo, rooms, cells, from, fromCell, mid, midCell, wall);
Append(pts, mid);
PullThrough(pts, graph, geo, rooms, cells, mid, midCell, to, toCell);
PullThrough(pts, graph, geo, rooms, cells, mid, midCell, to, toCell, wall);
NoteCrossing(pts, before, room, why ?? "look-in");
return;
}
}
int start = pts.Count;
PullThrough(pts, graph, geo, rooms, cells, from, fromCell, to, toCell);
PullThrough(pts, graph, geo, rooms, cells, from, fromCell, to, toCell, wall);
NoteCrossing(pts, start, room, why ?? "cross");
}
@ -750,9 +755,10 @@ internal static partial class DungeonPathfinder
// line, else the room's cells string-pulled with every leg that clear. Where the room is
// too tight for that, the crossing as before (0.5 m either side).
private static void PullThrough(List<NavPoint> pts, Dictionary<uint, DungeonNavNode> graph, DungeonGeometry geo,
DungeonRooms rooms, List<uint> cells, NavPoint from, uint fromCell, NavPoint to, uint toCell)
DungeonRooms rooms, List<uint> cells, NavPoint from, uint fromCell, NavPoint to, uint toCell,
double wall)
{
if (Clear(geo, cells, from, to, WallClearance)) return;
if (Clear(geo, cells, from, to, wall)) return;
// Through the room's own cells: the openings between them (or cell-centre midpoints),
// pushed off the walls like every other point.
@ -768,20 +774,21 @@ internal static partial class DungeonPathfinder
var na = graph[a]; var nb = graph[b];
corner = Note(Tag(new NavPoint { Type = NavPointType.Point, NS = (na.NS + nb.NS) * 0.5, EW = (na.EW + nb.EW) * 0.5, Z = (na.Z + nb.Z) * 0.5 / 240.0 }, "pull-midpoint"), a, a, b);
}
PushOffWalls(geo, corner, cells, CornerPushMax);
PushOffWalls(geo, corner, cells, CornerPushMax, wall);
corners.Add(corner);
}
corners.Add(to);
var strict = new List<NavPoint>();
if (StringPull(strict, geo, cells, from, corners, WallClearance))
if (StringPull(strict, geo, cells, from, corners, wall))
{
foreach (var p in strict) Append(pts, p);
return;
}
if (Clear(geo, cells, from, to, CrossingClearance)) return;
double loosest = Math.Min(CrossingClearance, wall);
if (Clear(geo, cells, from, to, loosest)) return;
var loose = new List<NavPoint>();
StringPull(loose, geo, cells, from, corners, CrossingClearance);
StringPull(loose, geo, cells, from, corners, loosest);
foreach (var p in loose) Append(pts, p);
}
@ -844,7 +851,7 @@ internal static partial class DungeonPathfinder
// The point a patrol visits to look into a room: the middle of its cell centres when that
// is on its floor, else the cell centre nearest that middle; then pushed off the walls.
private static NavPoint? RoomMiddle(Dictionary<uint, DungeonNavNode> graph, DungeonGeometry geo, List<uint> cells, out uint midCell)
private static NavPoint? RoomMiddle(Dictionary<uint, DungeonNavNode> graph, DungeonGeometry geo, List<uint> cells, double wall, out uint midCell)
{
midCell = 0;
double sx = 0, sy = 0, sz = 0;
@ -872,7 +879,7 @@ internal static partial class DungeonPathfinder
? Tag(WorldPoint(sx, sy, sz, false), "room-middle")
: Tag(WorldPoint(DungeonGeometry.NavToWorld(nearest.EW), DungeonGeometry.NavToWorld(nearest.NS), nearest.Z, false), "room-middle-cell");
// A one-cell dead end's origin is inside its end cap; a big room's middle can be a pillar.
PushOffWalls(geo, mid, cells, MiddlePushMax);
PushOffWalls(geo, mid, cells, MiddlePushMax, wall);
return mid;
}

View file

@ -451,98 +451,277 @@ internal static partial class DungeonPathfinder
private const double PatrolMinKeepFraction = 0.20;
/// <summary>
/// Returns the 2-core of the dungeon's walkable subgraph — the subset of
/// cells where every node has at least two walkable neighbours within the
/// set. Dead-end spurs of any length are stripped by repeatedly removing
/// leaf nodes (degree ≤ 1) until none remain. Only corridors that form
/// part of a cycle or connect two junctions survive, which is exactly the
/// "main route" a patrol bot should follow.
/// The cells the patrol walks, by <see cref="DungeonPatrolOptions.Coverage"/>:
/// Whole dungeon (default): every cell reachable from <paramref name="startCell"/> without
/// drops or hazards, less the dead-end areas of up to MaxDeadEndCells cells in all (closets,
/// a short corridor ending in a small room; <see cref="TrimDeadEndPockets"/>). Longer dead
/// ends are walked in until only that much is left ahead (a big room: to it), and back.
/// Loops only: the 2-core (cells on a loop or between two junctions), as before 2026-10-12:
/// every dead-end branch goes, however long. In a hive (0x6146 Matron Hive East: 524
/// reachable, 2-core 171) that leaves two thirds of the dungeon unpatrolled. Where the
/// hazards cut the loops (the 2-core collapses but the dungeon isn't linear), the
/// reachable cells less the small dead-end areas, as Whole dungeon.
/// Everything: every reachable cell.
///
/// Falls back to the full reachable set if the pruned graph would be too
/// small to be useful (small or purely linear dungeons).
/// A linear dungeon (its hazard-free 2-core under PatrolMinKeepNodes or 20% of reachable)
/// keeps every reachable cell, spurs included, whatever the coverage: there the spurs are
/// the dungeon.
///
/// <paramref name="rooms"/> (BuildRooms with the same hazards, when the map geometry is
/// there): dead-end areas are found room by room rather than cell by cell.
/// </summary>
private static HashSet<uint> GetMainRouteNodes(
internal static HashSet<uint> GetMainRouteNodes(
Dictionary<uint, DungeonNavNode> graph, uint startCell,
IReadOnlySet<uint>? hazardCells = null)
IReadOnlySet<uint>? hazardCells = null, DungeonPatrolOptions? options = null, DungeonRooms? rooms = null)
{
var o = options ?? DungeonPatrolOptions.Default;
var (reachable, pruned) = ReachableAndCore(graph, startCell, hazardCells);
int originalCount = reachable.Count;
// Fall back to full reachable set if pruning collapsed the graph - judged on the dungeon
// itself, not on what the hazards left. 2026-10-10, 0x6146: 3 acid cells + 35 lava-floor
// cells cut the loops (2-core 277 -> 68, under 20% of reachable), the fallback fired and
// the patrol walked into every dead-end 1-cell room. A dungeon with loops keeps its
// (smaller) 2-core around the hazards; only a dungeon that is linear without hazards, or
// a core under PatrolMinKeepNodes, falls back.
// Linear is judged on the dungeon itself, not on what the hazards left (2026-10-10, 0x6146:
// 3 acid cells + 35 lava-floor cells cut the loops, 2-core 277 -> 68).
bool collapsed = pruned.Count < PatrolMinKeepNodes || pruned.Count < originalCount * PatrolMinKeepFraction;
HashSet<uint> result = pruned;
string how = "2-core used";
if (collapsed && hazardCells != null && hazardCells.Count > 0)
bool linear = collapsed;
if (linear && hazardCells != null && hazardCells.Count > 0)
{
var (freeReach, freeCore) = ReachableAndCore(graph, startCell, null);
bool dungeonIsLinear = freeCore.Count < PatrolMinKeepNodes || freeCore.Count < freeReach.Count * PatrolMinKeepFraction;
if (!dungeonIsLinear)
{
// The hazards cut the loops; the rest of the dungeon hangs off them as long branches.
// Walk those, but not the short spurs (closets, 1-2 cell rooms behind a door).
result = TrimShortSpurs(graph, reachable, startCell, PatrolMaxSpurCells);
how = $"hazards cut the loops: all reachable cells but spurs of <= {PatrolMaxSpurCells} cells ({result.Count} kept)";
}
else { result = reachable; how = $"FALLBACK: patrol uses all {originalCount} reachable cells, dead ends included"; }
linear = freeCore.Count < PatrolMinKeepNodes || freeCore.Count < freeReach.Count * PatrolMinKeepFraction;
}
HashSet<uint> result;
string how;
if (o.Coverage == PatrolCoverage.Everything)
{
result = reachable;
how = $"everything: all {originalCount} reachable cells, dead ends included";
}
else if (linear)
{
result = reachable;
how = $"linear: patrol uses all {originalCount} reachable cells, dead ends included";
}
else if (o.Coverage == PatrolCoverage.LoopsOnly && !collapsed)
{
result = pruned;
how = $"loops only: the 2-core ({pruned.Count} cells)";
}
else
{
result = TrimDeadEndPockets(graph, reachable, startCell, o.MaxDeadEndCells, rooms, o.LookInRoomMeters);
how = (o.Coverage == PatrolCoverage.LoopsOnly ? "loops only, but hazards cut the loops: " : "")
+ $"all reachable cells but dead-end areas of <= {o.MaxDeadEndCells} cells{(rooms != null ? " (by room)" : "")} ({result.Count} kept)";
}
else if (collapsed) { result = reachable; how = $"FALLBACK: patrol uses all {originalCount} reachable cells, dead ends included"; }
if (PointLog != null)
MainRouteNote = $"main route from {startCell:X8}: {originalCount} reachable cells, 2-core {pruned.Count} "
+ $"({hazardCells?.Count ?? 0} hazard cells) -> " + how;
+ $"({hazardCells?.Count ?? 0} hazard cells) -> " + how + " [" + o.Describe() + "]";
return result;
}
/// <summary>Dead-end spurs this short (cells from the tip to the first junction) are left out
/// when the hazards collapsed the 2-core.</summary>
internal const int PatrolMaxSpurCells = 3;
/// <summary>Dead-end areas this small (all their cells, from where they leave the rest of the
/// dungeon) are left out of the patrol by default (Settings: Skip Dead Ends Up To).</summary>
internal const int PatrolMaxDeadEndCells = DungeonPatrolOptions.MaxDeadEndCellsDefault;
/// <summary>
/// <paramref name="cells"/> without every dead-end spur of at most <paramref name="maxSpur"/> cells:
/// from each tip (one walkable neighbour) walk inward through corridor cells (two neighbours)
/// to the first junction; a chain that short goes. One pass, so a long branch keeps its far end.
/// The hazard cells the patrol keeps out of: <paramref name="all"/> (the live set: floor
/// textures, pools sighted, cells marked by hand), less the lava/acid floor cells
/// (<paramref name="floorCells"/>) when <see cref="DungeonPatrolOptions.AvoidHazardFloors"/> is
/// off. A floor cell that is also in <paramref name="markedCells"/> (sighted or marked by hand,
/// DungeonHazardStore) stays avoided. Null when nothing is left.
/// </summary>
internal static HashSet<uint> TrimShortSpurs(Dictionary<uint, DungeonNavNode> graph, HashSet<uint> cells, uint keep, int maxSpur)
internal static IReadOnlySet<uint>? PatrolHazards(IReadOnlySet<uint>? all, IEnumerable<uint>? floorCells,
IReadOnlySet<uint>? markedCells, DungeonPatrolOptions? options)
{
int Degree(uint id)
{
if (!graph.TryGetValue(id, out var n)) return 0;
int d = 0;
foreach (uint nb in n.Neighbors)
if (cells.Contains(nb) && graph.TryGetValue(nb, out var o) && !IsDropEdge(n, o)) d++;
return d;
}
var drop = new HashSet<uint>();
foreach (uint tip in cells)
{
if (tip == keep || Degree(tip) != 1) continue;
var chain = new List<uint> { tip };
uint prev = 0, cur = tip;
bool shortSpur = false;
while (true)
{
uint next = 0;
foreach (uint nb in graph[cur].Neighbors)
if (nb != prev && cells.Contains(nb) && graph.TryGetValue(nb, out var o) && !IsDropEdge(graph[cur], o)) { next = nb; break; }
if (next == 0) break; // an isolated pair: leave it
int d = Degree(next);
if (d >= 3) { shortSpur = true; break; } // reached a junction
if (d <= 1 || next == keep) break; // the whole thing is a line, or runs into the start
chain.Add(next);
if (chain.Count > maxSpur) break; // long branch: keep it
prev = cur; cur = next;
}
if (shortSpur && chain.Count <= maxSpur) foreach (uint c in chain) drop.Add(c);
}
var result = new HashSet<uint>(cells);
result.ExceptWith(drop);
if (all == null || all.Count == 0) return all;
if ((options ?? DungeonPatrolOptions.Default).AvoidHazardFloors || floorCells == null) return all;
var result = new HashSet<uint>(all);
foreach (uint c in floorCells)
if (markedCells == null || !markedCells.Contains(c)) result.Remove(c);
return result;
}
/// <summary>
/// <paramref name="cells"/> without every dead-end area of at most <paramref name="maxCells"/>
/// cells. A dead-end area (a pocket) is everything that hangs off the rest by one cell or
/// room: a closet, a corridor with a small room at its end, a little loop off a corridor. It
/// is measured whole, so a short corridor ending in a 3-5 cell room goes (2026-10-13: the spur
/// walk this replaces stopped at the room, whose cells join each other, and kept it; raising
/// its limit changed nothing in 0x6146).
///
/// Pockets nest, and every one that small goes wherever it is: the patrol never walks into a
/// dead end of maxCells cells or fewer. A long branch is walked (and the small pockets off it
/// are not); where what is left of it ahead is that short, the patrol turns round. A branch to
/// a big room keeps it: a room spreading over <paramref name="bigRoomMeters"/> or more (the
/// look-in size) counts as too big to skip, so a pocket holding one is never dropped.
///
/// With <paramref name="rooms"/> (the map geometry is there) the pockets are found on the room
/// graph, a room's cells counted together: entering a room at all is entering it, and a
/// room's own corners (a star-shaped junction's arms) are not pockets of their own. Without,
/// cell by cell (and no room is big).
///
/// Rooted at <paramref name="keep"/> (the start): the side the start is on is never a pocket,
/// so a start in a closet keeps the closet and walks out of it. Everything hangs off the start
/// in that sense, so of what hangs off it the biggest part (the rest of the dungeon, or all
/// of it when the start is on a loop) always stays, however small the dungeon.
/// </summary>
internal static HashSet<uint> TrimDeadEndPockets(Dictionary<uint, DungeonNavNode> graph, HashSet<uint> cells, uint keep,
int maxCells, DungeonRooms? rooms = null,
double bigRoomMeters = DungeonPatrolOptions.LookInRoomDefault)
{
var result = new HashSet<uint>(cells);
if (maxCells <= 0 || cells.Count == 0) return result;
if (rooms == null || !rooms.RoomOf.TryGetValue(keep, out int keepRoom))
{
result.ExceptWith(DroppedPockets(FindDeadEndPockets(CellAdjacency(graph, cells), _ => 1, keep), maxCells));
return result;
}
var (adj, weight) = RoomAdjacency(graph, cells, rooms);
int Weight(uint r) => RoomSpreadMeters(graph, rooms.Cells[(int)r]) >= bigRoomMeters ? maxCells + 1 : weight[r];
var droppedRooms = DroppedPockets(FindDeadEndPockets(adj, Weight, (uint)keepRoom), maxCells);
foreach (uint c in cells)
if (rooms.RoomOf.TryGetValue(c, out int r) && droppedRooms.Contains((uint)r)) result.Remove(c);
return result;
}
/// <summary>The nodes of every pocket of at most <paramref name="maxSize"/>, but the biggest
/// hanging off each root of the walk (the dungeon itself, seen from the start).</summary>
private static HashSet<uint> DroppedPockets(DeadEndPockets p, int maxSize)
{
var main = new HashSet<uint>();
foreach (uint root in p.Roots)
{
DeadEndPocket? best = null;
foreach (var q in p.All)
if (q.Attach == root && (best == null || q.Size > best.Value.Size)) best = q;
if (best != null) main.Add(best.Value.Root);
}
var dropped = new HashSet<uint>();
foreach (var q in p.All)
if (q.Size <= maxSize && !main.Contains(q.Root) && !dropped.Contains(q.Root))
foreach (uint c in p.NodesOf(q)) dropped.Add(c);
return dropped;
}
/// <summary>The room graph of <paramref name="cells"/>: a node per room (its index) with cells in
/// the set, weighted by those cells, joined where two of their cells are walkable neighbours.</summary>
internal static (Dictionary<uint, List<uint>> Adj, Dictionary<uint, int> Weight) RoomAdjacency(
Dictionary<uint, DungeonNavNode> graph, HashSet<uint> cells, DungeonRooms rooms)
{
var weight = new Dictionary<uint, int>();
foreach (uint c in cells)
if (rooms.RoomOf.TryGetValue(c, out int r)) weight[(uint)r] = weight.GetValueOrDefault((uint)r) + 1;
var adj = new Dictionary<uint, List<uint>>(weight.Count);
foreach (uint r in weight.Keys) adj[r] = new List<uint>();
foreach (var (c, nbs) in CellAdjacency(graph, cells))
{
if (!rooms.RoomOf.TryGetValue(c, out int ra)) continue;
foreach (uint nb in nbs)
if (rooms.RoomOf.TryGetValue(nb, out int rb) && ra != rb && !adj[(uint)ra].Contains((uint)rb))
adj[(uint)ra].Add((uint)rb);
}
return (adj, weight);
}
/// <summary>The walkable neighbours (no drops) of each cell inside <paramref name="cells"/>, each once.</summary>
private static Dictionary<uint, List<uint>> CellAdjacency(Dictionary<uint, DungeonNavNode> graph, HashSet<uint> cells)
{
var adj = new Dictionary<uint, List<uint>>(cells.Count);
foreach (uint c in cells)
{
var list = new List<uint>();
if (graph.TryGetValue(c, out var n))
foreach (uint nb in n.Neighbors)
if (nb != c && cells.Contains(nb) && graph.TryGetValue(nb, out var o) && !IsDropEdge(n, o) && !list.Contains(nb))
list.Add(nb);
adj[c] = list;
}
return adj;
}
/// <summary>A dead-end area: <see cref="Root"/> and everything behind it hang off the rest by
/// <see cref="Attach"/> alone. <see cref="Size"/> is its weight (cells), Attach not counted.</summary>
internal readonly record struct DeadEndPocket(uint Attach, uint Root, int Size);
/// <summary>Every dead-end area of a graph, nested ones included (<see cref="FindDeadEndPockets"/>).</summary>
internal sealed class DeadEndPockets
{
internal readonly List<uint> Order = new();
internal readonly Dictionary<uint, int> Disc = new();
internal readonly Dictionary<uint, int> Count = new();
/// <summary>Every pocket, in depth-first order of their roots (outer ones first).</summary>
public readonly List<DeadEndPocket> All = new();
/// <summary>Where the walk started: keep, then a node of each part not connected to it.</summary>
public readonly List<uint> Roots = new();
/// <summary>The pocket's nodes: its root's subtree, a run of the depth-first order.</summary>
public IEnumerable<uint> NodesOf(DeadEndPocket p)
{
for (int k = Disc[p.Root], end = k + Count[p.Root]; k < end; k++) yield return Order[k];
}
}
/// <summary>
/// The dead-end areas of a graph seen from <paramref name="keep"/>: a depth-first walk from it
/// (Tarjan's cut vertices), where a child w of v whose subtree has no way round v (low[w] >=
/// disc[v]) is a pocket hanging off v, weighing the sum of its nodes' weights. Nodes not
/// connected to keep are walked from the lowest id up.
/// </summary>
internal static DeadEndPockets FindDeadEndPockets(Dictionary<uint, List<uint>> adj, Func<uint, int> weight, uint keep)
{
var r = new DeadEndPockets();
var disc = r.Disc;
var count = r.Count;
var order = r.Order;
var size = new Dictionary<uint, int>(adj.Count);
var low = new Dictionary<uint, int>(adj.Count);
var parent = new Dictionary<uint, uint>(adj.Count);
var roots = new List<uint>();
if (adj.ContainsKey(keep)) roots.Add(keep);
var rest = new List<uint>(adj.Keys);
rest.Sort();
roots.AddRange(rest);
var stack = new Stack<(uint Node, int Next)>();
foreach (uint root in roots)
{
if (disc.ContainsKey(root)) continue;
r.Roots.Add(root);
disc[root] = low[root] = order.Count; order.Add(root); count[root] = 1; size[root] = weight(root);
stack.Push((root, 0));
while (stack.Count > 0)
{
var (v, i) = stack.Pop();
var nbs = adj[v];
if (i < nbs.Count)
{
stack.Push((v, i + 1));
uint w = nbs[i];
if (!adj.ContainsKey(w)) continue;
if (!disc.ContainsKey(w))
{
parent[w] = v;
disc[w] = low[w] = order.Count; order.Add(w); count[w] = 1; size[w] = weight(w);
stack.Push((w, 0));
}
else if (!(parent.TryGetValue(v, out uint pv) && pv == w))
low[v] = Math.Min(low[v], disc[w]);
continue;
}
// v finished: hand its low-link, node count and weight up to its parent.
if (parent.TryGetValue(v, out uint p))
{
low[p] = Math.Min(low[p], low[v]);
count[p] += count[v];
size[p] += size[v];
}
}
}
foreach (var (w, v) in parent)
if (low[w] >= disc[v]) r.All.Add(new DeadEndPocket(v, w, size[w]));
r.All.Sort((a, b) => disc[a.Root].CompareTo(disc[b.Root]));
return r;
}
/// <summary>The cells reachable from startCell (no drops, no hazards) and their 2-core.</summary>
private static (HashSet<uint> Reachable, HashSet<uint> Core) ReachableAndCore(
Dictionary<uint, DungeonNavNode> graph, uint startCell, IReadOnlySet<uint>? hazardCells)
@ -620,15 +799,19 @@ internal static partial class DungeonPathfinder
Dictionary<uint, DungeonNavNode> graph,
uint startCell,
IReadOnlySet<uint>? hazardCells = null,
DungeonGeometry? geo = null)
DungeonGeometry? geo = null,
DungeonPatrolOptions? options = null)
{
var mainRoute = GetMainRouteNodes(graph, startCell, hazardCells);
var o = (options ?? DungeonPatrolOptions.Default).Clamped();
// Dead ends are judged room by room when the rooms can be made (the room patrol below).
var rooms = geo != null && geo.DoorwayCount > 0 ? BuildRooms(graph, geo, hazardCells) : null;
var mainRoute = GetMainRouteNodes(graph, startCell, hazardCells, o, rooms);
// With the dungeon map geometry: the same coverage over rooms instead of cells, rooms
// crossed directly, doorways taken straight on (DungeonPathfinder.Rooms.cs).
if (geo != null && geo.DoorwayCount > 0)
{
var byRoom = BuildRoomPatrol(graph, startCell, mainRoute, hazardCells, geo);
var byRoom = BuildRoomPatrol(graph, startCell, mainRoute, hazardCells, geo, o);
if (byRoom != null && byRoom.Points.Count > 0) return byRoom;
}
@ -714,7 +897,7 @@ internal static partial class DungeonPathfinder
// off from every doorway): the cell walk's points still keep off the walls.
if (geo != null)
foreach (var p in route.Points)
PushOffWalls(geo, Tag(p, "cell-walk"), null, CornerPushMax);
PushOffWalls(geo, Tag(p, "cell-walk"), null, CornerPushMax, o.WallClearance);
return route;
}

View file

@ -0,0 +1,110 @@
// DungeonPatrolOptions: the player-tunable side of the dungeon patrol (Settings > Navigation >
// Dungeon Patrol). Passed into DungeonPathfinder.BuildPatrolRoute as a value, never kept in a
// static: every build says what it was built with, and a reload starts from the settings again.
// The defaults are the patrol as it was before the settings existed (2026-10-12, f15c153), but
// for the dead-end limit: since 2026-10-13 it counts whole dead-end areas, default 10 (was 3).
using System;
using System.Collections.Generic;
using System.Globalization;
namespace RynthCore.Plugin.RynthAi;
/// <summary>Which cells the patrol walks (Settings > Navigation > Dungeon Patrol > Coverage).</summary>
internal enum PatrolCoverage
{
/// <summary>Every reachable cell but dead-end areas of up to MaxDeadEndCells cells (2026-10-12 on).</summary>
WholeDungeon = 0,
/// <summary>Only the loops and the corridors between junctions (the 2-core; before 2026-10-12).</summary>
LoopsOnly = 1,
/// <summary>Every reachable cell, every dead end included.</summary>
Everything = 2,
}
internal sealed record DungeonPatrolOptions
{
public const int MaxDeadEndCellsMin = 0, MaxDeadEndCellsMax = 30, MaxDeadEndCellsDefault = 10;
public const double WallClearanceMin = 0.5, WallClearanceMax = 2.0, WallClearanceDefault = 1.0;
public const double LookInRoomMin = 3.0, LookInRoomMax = 40.0, LookInRoomDefault = 10.0;
public static readonly DungeonPatrolOptions Default = new();
public PatrolCoverage Coverage { get; init; } = PatrolCoverage.WholeDungeon;
/// <summary>Whole dungeon (and Loops only when hazards cut the loops): dead-end areas this
/// small (all their cells: a closet, a short corridor with a small room at its end) are left
/// out, and the patrol turns round where a longer dead end has only this much left ahead.
/// A big room (LookInRoomMeters) is never left out. 0 = none left out.
/// <see cref="DungeonPathfinder.TrimDeadEndPockets"/>. Until 2026-10-13 a spur limit (cells from
/// a tip to the first junction, default 3), which kept every corridor that ended in a room.</summary>
public int MaxDeadEndCells { get; init; } = MaxDeadEndCellsDefault;
/// <summary>Lava/acid floor cells (Detector C, HazardTextures.txt) are kept out of the patrol.
/// Cells marked by hand or sighted as pools are avoided either way. Applied by the caller,
/// which knows which cells are which (<see cref="DungeonPathfinder.PatrolHazards"/>).</summary>
public bool AvoidHazardFloors { get; init; } = true;
/// <summary>Every point laid keeps at least this far (metres) from walls where there is room.</summary>
public double WallClearance { get; init; } = WallClearanceDefault;
/// <summary>A room at least this big (metres across its cell centres) that the patrol only
/// skirts or leaves by the doorway it came in by gets a walk to its middle and back.</summary>
public double LookInRoomMeters { get; init; } = LookInRoomDefault;
/// <summary>The options with every value in range (a hand-edited profile or a remote setting).</summary>
public DungeonPatrolOptions Clamped() => this with
{
Coverage = Enum.IsDefined(Coverage) ? Coverage : PatrolCoverage.WholeDungeon,
MaxDeadEndCells = Math.Clamp(MaxDeadEndCells, MaxDeadEndCellsMin, MaxDeadEndCellsMax),
WallClearance = double.IsFinite(WallClearance) ? Math.Clamp(WallClearance, WallClearanceMin, WallClearanceMax) : WallClearanceDefault,
LookInRoomMeters = double.IsFinite(LookInRoomMeters) ? Math.Clamp(LookInRoomMeters, LookInRoomMin, LookInRoomMax) : LookInRoomDefault,
};
public static string CoverageName(PatrolCoverage c) => c switch
{
PatrolCoverage.LoopsOnly => "loops only",
PatrolCoverage.Everything => "everything",
_ => "whole dungeon",
};
/// <summary>For the "main route from ..." diagnostic line and PatrolProof.</summary>
public string Describe()
{
var inv = CultureInfo.InvariantCulture;
string spurs = Coverage == PatrolCoverage.Everything ? "" : $", skip dead ends <= {MaxDeadEndCells}";
return $"coverage {CoverageName(Coverage)}{spurs}, lava/acid floors {(AvoidHazardFloors ? "avoided" : "walked")}, "
+ $"walls {WallClearance.ToString("0.0#", inv)} m, look into rooms >= {LookInRoomMeters.ToString("0.#", inv)} m";
}
}
/// <summary>
/// Notices a patrol setting changed while a patrol runs and says when to rebuild it: once the
/// new settings have stayed put for <see cref="SettleMs"/> (the Settings panel saves on every
/// click of a +/- step, and a rebuild per click would restart the lap each time). One per
/// plugin instance, so nothing outlives a reload.
/// </summary>
internal sealed class PatrolSettingsWatch
{
public const long SettleMs = 1000;
private DungeonPatrolOptions? _built, _pending;
private long _pendingSince;
/// <summary>The settings the running patrol was built with (null = none built yet).</summary>
public DungeonPatrolOptions? Built => _built;
public void MarkBuilt(DungeonPatrolOptions options)
{
_built = options;
_pending = null;
}
/// <summary>True when <paramref name="current"/> differs from what the patrol was built with
/// and has not changed for SettleMs.</summary>
public bool ShouldRebuild(DungeonPatrolOptions current, long nowMs)
{
if (_built == null || current.Equals(_built)) { _pending = null; return false; }
if (!current.Equals(_pending)) { _pending = current; _pendingSince = nowMs; return false; }
return nowMs - _pendingSince >= SettleMs;
}
}

View file

@ -0,0 +1,355 @@
// GroundLootController.cs — picks up loose ground items that match the active loot profile
// (UB-IT AutoGroundLoot, driven by RynthAi's own loot rules and corpse range).
//
// * Scan: every GroundScanIntervalMs, objects lying in the world (readable ownership with
// no container / wielder, finite distance) within the corpse max range, minus scenery /
// creatures / doors / corpses, are classified with the same ClassifyItemAgainstProfile
// the corpse looter uses. Stat-gated rules get a server appraisal first (a few per scan),
// then a best-effort classify once GroundAppraiseWaitMs passes.
// * Pickup: only once the activity arbiter has handed the tick to Looting (HasLootWork sees
// the matches, so navigation is already stopped). MoveItemExternal(item → player); ACE
// walks the character to the item and picks it up. Confirmed when the item leaves the
// ground, retried up to GroundMaxPickupAttempts, then put on a long cooldown.
// * Corpses always win: ground loot only runs when no corpse is claimed or open.
using System;
using System.Collections.Generic;
using RynthCore.Plugin.RynthAi.LegacyUi;
namespace RynthCore.Plugin.RynthAi;
public sealed partial class RynthAiPlugin
{
private const long GroundScanIntervalMs = 300;
/// <summary>Classify best-effort after waiting this long for an item's appraisal.</summary>
private const long GroundAppraiseWaitMs = 3_000;
/// <summary>Server move-to plus pickup animation must finish inside this window before a retry.</summary>
private const long GroundPickupVerifyMs = 5_000;
/// <summary>A claimed item whose pickup could never be sent (client stayed busy) is dropped after this.</summary>
private const long GroundClaimStallMs = 10_000;
/// <summary>Items that matched no rule are re-checked after this (profile edits, late appraisal).</summary>
private const long GroundLeaveCooldownMs = 60_000;
private const long GroundFailCooldownMs = 300_000;
private const int GroundMaxPickupAttempts = 3;
private const int GroundAppraisalsPerScan = 2;
private long _groundLastScanAt;
private int _groundMatchesInRange;
private int _groundTargetId;
private long _groundTargetSince;
private long _groundPickupRequestedAt;
private int _groundPickupAttempts;
private string _groundTargetName = string.Empty;
private string _groundTargetAction = string.Empty;
private string _groundTargetRule = string.Empty;
private bool _groundTargetIsSalvage;
/// <summary>id → ms before which the item is not re-evaluated (left, failed or gone).</summary>
private readonly Dictionary<int, long> _groundSkipUntil = new();
/// <summary>id → ms of the first appraisal request (bounds the wait for stat data).</summary>
private readonly Dictionary<int, long> _groundAppraiseAt = new();
/// <summary>A pickup request is out and not yet confirmed — corpse claims wait for it.</summary>
private bool GroundPickupInFlight => _groundTargetId != 0 && _groundPickupRequestedAt != 0;
/// <summary>Arbiter input: a claimed ground item, or matching ground items seen by the last scan.</summary>
private bool HasGroundLootWork(LegacyUiSettings settings)
=> settings.EnableGroundLoot && (_groundTargetId != 0 || _groundMatchesInRange > 0);
/// <summary>
/// One ground-loot step (pump thread, called from TickCorpseOpening when no corpse is
/// claimed or open). Gating for macro / looting / buffing / combat is done by the caller.
/// </summary>
private void TickGroundLoot(LegacyUiSettings settings, double maxMeters)
{
if (!settings.EnableGroundLoot || _objectCache == null || _playerId == 0)
{
ResetGroundLoot(clearCaches: false);
return;
}
long now = CorpseNowMs;
if (_groundTargetId != 0)
{
TickGroundTarget(maxMeters, now);
return;
}
if (now - _groundLastScanAt < GroundScanIntervalMs)
return;
_groundLastScanAt = now;
PruneGroundCollections(now);
WorldObject? best = ScanGroundLoot(settings, maxMeters, now, out double bestDist,
out string action, out string rule, out bool salvage);
if (best == null)
return;
// HasLootWork reports the match; wait until the arbiter actually gives Looting the tick.
if (_activity != BotActivity.Looting)
return;
_groundTargetId = best.Id;
_groundTargetSince = now;
_groundPickupRequestedAt = 0;
_groundPickupAttempts = 0;
_groundTargetName = best.Name ?? string.Empty;
_groundTargetAction = action;
_groundTargetRule = rule;
_groundTargetIsSalvage = salvage;
if (!(_navStopIssued && _navStoppedFor == BotActivity.Looting))
StopNavFor(BotActivity.Looting);
LootDiag($"[RynthAi] Ground loot: claimed 0x{(uint)best.Id:X8} '{_groundTargetName}' dist={bestDist:F1}m [{action}] rule='{rule}'.");
TryRequestGroundPickup(now);
}
/// <summary>
/// Finds the nearest ground item that matches the loot profile and counts all matches
/// in range (for <see cref="HasGroundLootWork"/>). Requests appraisal for stat-gated items.
/// </summary>
private WorldObject? ScanGroundLoot(LegacyUiSettings settings, double maxMeters, long now,
out double bestDist, out string bestAction, out string bestRule, out bool bestSalvage)
{
bestDist = double.MaxValue;
bestAction = bestRule = string.Empty;
bestSalvage = false;
_groundMatchesInRange = 0;
if (_objectCache == null || maxMeters <= 0.25)
return null;
// The profile loaders chat on every failed load; a 300 ms scan must not trigger that.
string profilePath = (settings.CurrentLootPath ?? string.Empty).Trim().Trim('"');
if (profilePath.Length == 0 || !System.IO.File.Exists(profilePath))
return null;
int playerId = unchecked((int)_playerId);
int appraisalsSent = 0;
WorldObject? best = null;
foreach (WorldObject wo in _objectCache.AllKnownObjects())
{
if (wo.Id == playerId || IsGroundLootExcludedClass(wo.ObjectClass))
continue;
if (_groundSkipUntil.TryGetValue(wo.Id, out long until))
{
if (until > now) continue;
_groundSkipUntil.Remove(wo.Id);
}
if (string.IsNullOrWhiteSpace(wo.Name))
continue;
// Carried / contained items have no world position, so Distance is MaxValue for them.
double dist = _objectCache.Distance(playerId, wo.Id);
if (dist > maxMeters)
continue;
if (!_objectCache.IsOnGround(wo.Id))
continue;
uint uid = unchecked((uint)wo.Id);
bool appraised = Host.HasHasAppraisalData && Host.HasAppraisalData(uid);
if (!appraised && ItemNeedsAppraisalForLoot(wo))
{
if (!_groundAppraiseAt.TryGetValue(wo.Id, out long firstAsk))
{
if (appraisalsSent < GroundAppraisalsPerScan && _busyCount == 0 && Host.RequestId(uid))
{
_groundAppraiseAt[wo.Id] = now;
appraisalsSent++;
}
continue;
}
if (now - firstAsk < GroundAppraiseWaitMs)
continue;
// Appraisal never arrived — classify best-effort, like the corpse assess window.
}
bool keep = ClassifyItemAgainstProfile(wo, settings, out string action, out bool salvage, out string rule);
LootDiag($"[LootEval] ground '{wo.Name}' cls={wo.ObjectClass} dist={dist:F1}m appraised={appraised} -> " +
(keep ? $"KEEP [{action}] rule='{rule}'" : "leave"));
if (!keep)
{
_groundSkipUntil[wo.Id] = now + GroundLeaveCooldownMs;
continue;
}
_groundMatchesInRange++;
if (dist < bestDist)
{
best = wo;
bestDist = dist;
bestAction = action;
bestRule = rule;
bestSalvage = salvage;
}
}
return best;
}
/// <summary>Follows a claimed item: confirm pickup, retry, or give up.</summary>
private void TickGroundTarget(double maxMeters, long now)
{
if (_objectCache == null)
return;
int id = _groundTargetId;
WorldObject? item = _objectCache[id];
if (item == null)
{
// Deleted from the world: decayed or another player took it.
LootDiag($"[RynthAi] Ground loot: 0x{(uint)id:X8} '{_groundTargetName}' is gone.");
FinishGroundTarget(now, GroundFailCooldownMs);
return;
}
if (!_objectCache.IsOnGround(id) && _objectCache.GetContainerId(id) != 0)
{
LootDiag($"[RynthAi] Ground loot: pickup confirmed for 0x{(uint)id:X8} '{_groundTargetName}'.");
ChatLine($"[RynthAi] Looted [{_groundTargetAction}] {_groundTargetName} (ground)");
if (_groundTargetIsSalvage)
_salvageManager?.EnqueueItem(unchecked((uint)id));
FinishGroundTarget(now, GroundFailCooldownMs);
return;
}
int playerId = unchecked((int)_playerId);
double dist = _objectCache.Distance(playerId, id);
if (dist > Math.Max(maxMeters * 1.5, maxMeters + 2.0))
{
LootDiag($"[RynthAi] Ground loot: 0x{(uint)id:X8} '{_groundTargetName}' drifted out of range ({dist:F1}m); releasing.");
FinishGroundTarget(now, GroundLeaveCooldownMs);
return;
}
if (_groundPickupRequestedAt == 0)
{
if (now - _groundTargetSince > GroundClaimStallMs)
{
LootDiag($"[RynthAi] Ground loot: could not send pickup for 0x{(uint)id:X8} (client busy); releasing.");
FinishGroundTarget(now, GroundLeaveCooldownMs);
return;
}
TryRequestGroundPickup(now);
return;
}
if (now - _groundPickupRequestedAt < GroundPickupVerifyMs)
return;
if (_groundPickupAttempts >= GroundMaxPickupAttempts)
{
LootDiag($"[RynthAi] Ground loot: pickup failed for 0x{(uint)id:X8} '{_groundTargetName}' after {_groundPickupAttempts} attempt(s).");
FinishGroundTarget(now, GroundFailCooldownMs);
return;
}
TryRequestGroundPickup(now);
}
/// <summary>Sends the pickup (item → player's main pack) when the client isn't busy.</summary>
private void TryRequestGroundPickup(long now)
{
if (_busyCount > 0 || _groundTargetId == 0)
return;
uint uid = unchecked((uint)_groundTargetId);
Host.SelectItem(uid);
bool sent = Host.HasMoveItemExternal
? Host.MoveItemExternal(uid, _playerId, 0)
: Host.UseObject(uid);
_groundPickupAttempts++;
_groundPickupRequestedAt = now;
LootDiag($"[RynthAi] Ground loot: pickup {(sent ? "sent" : "rejected")} for 0x{uid:X8} attempt {_groundPickupAttempts}.");
}
/// <summary>Releases the claimed item and parks it for <paramref name="cooldownMs"/>.</summary>
private void FinishGroundTarget(long now, long cooldownMs)
{
if (_groundTargetId != 0)
{
_groundSkipUntil[_groundTargetId] = now + cooldownMs;
_groundAppraiseAt.Remove(_groundTargetId);
}
_groundTargetId = 0;
_groundTargetSince = 0;
_groundPickupRequestedAt = 0;
_groundPickupAttempts = 0;
_groundTargetName = _groundTargetAction = _groundTargetRule = string.Empty;
_groundTargetIsSalvage = false;
_groundLastScanAt = 0; // rescan straight away for the next item
}
/// <summary>Drops the claim (and optionally the per-item caches, e.g. on logout or /ra groundloot scan).</summary>
private void ResetGroundLoot(bool clearCaches)
{
_groundTargetId = 0;
_groundTargetSince = 0;
_groundPickupRequestedAt = 0;
_groundPickupAttempts = 0;
_groundTargetName = _groundTargetAction = _groundTargetRule = string.Empty;
_groundTargetIsSalvage = false;
_groundMatchesInRange = 0;
if (!clearCaches)
return;
_groundSkipUntil.Clear();
_groundAppraiseAt.Clear();
_groundLastScanAt = 0;
}
/// <summary>Keeps the per-item maps bounded.</summary>
private void PruneGroundCollections(long now)
{
if (_groundSkipUntil.Count > 512)
{
var expired = new List<int>();
foreach (var kv in _groundSkipUntil)
if (kv.Value <= now) expired.Add(kv.Key);
foreach (int k in expired) _groundSkipUntil.Remove(k);
}
if (_groundAppraiseAt.Count > 256)
{
var stale = new List<int>();
foreach (var kv in _groundAppraiseAt)
if (now - kv.Value > GroundLeaveCooldownMs) stale.Add(kv.Key);
foreach (int k in stale) _groundAppraiseAt.Remove(k);
}
}
/// <summary>Scenery, creatures, fixtures and containers are never picked up from the ground.</summary>
private static bool IsGroundLootExcludedClass(AcObjectClass cls) => cls is
AcObjectClass.Unknown or AcObjectClass.Monster or AcObjectClass.Player or AcObjectClass.Npc
or AcObjectClass.Vendor or AcObjectClass.Portal or AcObjectClass.Door or AcObjectClass.Corpse
or AcObjectClass.Lifestone or AcObjectClass.Sign or AcObjectClass.Housing or AcObjectClass.Container
or AcObjectClass.CombatPet or AcObjectClass.Services;
/// <summary>/ra groundloot [on|off|status|scan]</summary>
private void HandleGroundLootCommand(string[] parts)
{
var settings = _dashboard?.Settings;
if (settings == null) { ChatLine("[RynthAi] Not logged in."); return; }
string verb = parts.Length >= 3 ? parts[2].Trim().ToLowerInvariant() : "status";
switch (verb)
{
case "on":
settings.EnableGroundLoot = true;
_dashboard?.SaveSettings();
ChatLine("[RynthAi] Ground loot ON (uses the loot profile and the corpse max range).");
break;
case "off":
settings.EnableGroundLoot = false;
ResetGroundLoot(clearCaches: true);
_dashboard?.SaveSettings();
ChatLine("[RynthAi] Ground loot OFF.");
break;
case "scan":
ResetGroundLoot(clearCaches: true);
ChatLine("[RynthAi] Ground loot: cleared skip list; rescanning.");
break;
default:
double yards = settings.CorpseApproachRangeMax;
string target = _groundTargetId != 0 ? $" | target '{_groundTargetName}' attempts={_groundPickupAttempts}" : string.Empty;
ChatLine($"[RynthAi] Ground loot {(settings.EnableGroundLoot ? "ON" : "OFF")} | range {yards:0.#} yd | " +
$"looting {(settings.EnableLooting ? "on" : "off")} | matches in range {_groundMatchesInRange} | " +
$"skipped {_groundSkipUntil.Count}{target}");
break;
}
}
}

View file

@ -0,0 +1,223 @@
// CombatHudTracker.cs — Pump-thread feed for the Mini Remote's Target and Summon rows.
//
// Target the creature combat is attacking (CombatManager.activeTargetId): name, health
// ratio from the object cache, distance.
// Summon the player's pet ("<Player>'s <Pet>" in the landscape): health ratio (polled with
// QueryHealth) and time left (RemainingLifespan from one appraisal, then counted
// down locally).
//
// The render thread only reads the published immutable snapshot.
using System;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthAi.Huds;
/// <summary>Immutable view of the attack target and the active summon (render thread safe).</summary>
internal sealed record CombatHudSnapshot(
int TargetId,
string TargetName,
float TargetHealth, // 0..1, -1 = no health received yet
double TargetDistance, // yards, < 0 = unknown
int PetId,
string PetName,
float PetHealth, // 0..1, -1 = no health received yet
long PetExpiresAtMs, // Environment.TickCount64 deadline, 0 = lifespan unknown
int PetLifespanSec, // total lifespan, 0 = unknown
long PetSeenAtMs) // when this pet first appeared
{
public static readonly CombatHudSnapshot Empty = new(0, string.Empty, -1f, -1, 0, string.Empty, -1f, 0, 0, 0);
}
internal sealed class CombatHudTracker
{
private const uint StypeLifespan = 267;
private const uint StypeRemainingLifespan = 268;
private const long ThinkIntervalMs = 250;
// QueryHealth makes the server stream that creature's health to us instead of the previous
// query's, so each pet poll is followed by a re-query of the combat / selected target.
private const long PetHealthPollMs = 3000;
private const long AppraiseRetryMs = 5000;
private const int AppraiseMaxAttempts = 3;
private const long PlayerNameRefreshMs = 30_000;
private readonly RynthCoreHost _host;
private readonly Func<WorldObjectCache?> _cache;
private readonly Func<int> _attackTargetId;
private volatile CombatHudSnapshot _snapshot = CombatHudSnapshot.Empty;
private long _lastThinkAt;
private string _playerName = string.Empty;
private long _playerNameAt;
// Current pet bookkeeping.
private int _petId;
private long _petSeenAt;
private long _petExpiresAt;
private int _petLifespanSec;
private int _appraiseAttempts;
private long _lastAppraiseAt;
private long _lastPetHealthAt;
public CombatHudTracker(RynthCoreHost host, Func<WorldObjectCache?> cache, Func<int> attackTargetId)
{
_host = host;
_cache = cache;
_attackTargetId = attackTargetId;
}
/// <summary>Latest target / summon view.</summary>
public CombatHudSnapshot Snapshot => _snapshot;
private static long NowMs => Environment.TickCount64;
/// <summary>Refreshes the snapshot (pump thread). Cheap when called every tick.</summary>
public void Tick()
{
long now = NowMs;
if (now - _lastThinkAt < ThinkIntervalMs) return;
_lastThinkAt = now;
var cache = _cache();
if (cache == null) { _snapshot = CombatHudSnapshot.Empty; return; }
int playerId = unchecked((int)_host.GetPlayerId());
int targetId = _attackTargetId();
// ── Attack target ──
string targetName = string.Empty;
float targetHealth = -1f;
double targetDist = -1;
if (targetId != 0)
{
targetName = cache[targetId]?.Name ?? string.Empty;
if (targetName.Length == 0 && _host.TryGetObjectName(unchecked((uint)targetId), out string n)) targetName = n;
if (targetName.Length == 0) targetName = $"0x{(uint)targetId:X8}";
targetHealth = cache.GetHealthRatio(targetId);
if (playerId != 0)
{
double d = cache.Distance(playerId, targetId);
targetDist = d < double.MaxValue ? d : -1;
}
}
// ── Summon ──
var pet = FindOwnPet(cache);
string petName = string.Empty;
float petHealth = -1f;
if (pet == null)
{
ForgetPet();
}
else
{
if (pet.Id != _petId) StartTrackingPet(pet.Id, now);
petName = StripOwner(pet.Name);
TickPetLifespan(now);
TickPetHealth(now, targetId);
petHealth = cache.GetHealthRatio(_petId);
}
_snapshot = new CombatHudSnapshot(targetId, targetName, targetHealth, targetDist,
_petId, petName, petHealth, _petExpiresAt, _petLifespanSec, _petSeenAt);
}
public void OnLogout()
{
ForgetPet();
_playerName = string.Empty;
_snapshot = CombatHudSnapshot.Empty;
}
// ── Pet ─────────────────────────────────────────────────────────────────
private WorldObject? FindOwnPet(WorldObjectCache cache)
{
string me = PlayerName();
if (me.Length == 0) return null;
string prefix = me + "'s ";
foreach (var wo in cache.GetLandscape())
if (wo != null && !string.IsNullOrEmpty(wo.Name) && wo.Name.StartsWith(prefix, StringComparison.Ordinal))
return wo;
return null;
}
private string PlayerName()
{
long now = NowMs;
if (_playerName.Length > 0 && now - _playerNameAt < PlayerNameRefreshMs) return _playerName;
uint pid = _host.GetPlayerId();
if (pid != 0 && _host.TryGetObjectName(pid, out string n) && !string.IsNullOrEmpty(n))
{
_playerName = n;
_playerNameAt = now;
}
return _playerName;
}
/// <summary>"Silent's Fire Banshee" → "Fire Banshee".</summary>
private string StripOwner(string name)
{
string prefix = _playerName + "'s ";
return _playerName.Length > 0 && name.StartsWith(prefix, StringComparison.Ordinal) ? name[prefix.Length..] : name;
}
private void StartTrackingPet(int id, long now)
{
_petId = id;
_petSeenAt = now;
_petExpiresAt = 0;
_petLifespanSec = 0;
_appraiseAttempts = 0;
_lastAppraiseAt = 0;
_lastPetHealthAt = 0;
RynthLog.Trace(LogCat.Huds, $"summon tracked 0x{(uint)id:X8}");
}
private void ForgetPet()
{
_petId = 0;
_petSeenAt = 0;
_petExpiresAt = 0;
_petLifespanSec = 0;
_appraiseAttempts = 0;
}
/// <summary>
/// Appraises the new pet (at most <see cref="AppraiseMaxAttempts"/> times) and anchors the
/// countdown on the first RemainingLifespan the server returns. The pet's guid is new, so
/// any cached value belongs to this pet.
/// </summary>
private void TickPetLifespan(long now)
{
if (_petExpiresAt != 0) return;
uint uid = unchecked((uint)_petId);
if (_host.HasGetObjectIntProperty && _host.TryGetObjectIntProperty(uid, StypeRemainingLifespan, out int remaining) && remaining > 0)
{
_petExpiresAt = now + remaining * 1000L;
if (_host.TryGetObjectIntProperty(uid, StypeLifespan, out int total) && total > 0)
_petLifespanSec = Math.Max(total, remaining);
RynthLog.Trace(LogCat.Huds, $"summon 0x{uid:X8}: {remaining}s left of {_petLifespanSec}s");
return;
}
if (_appraiseAttempts >= AppraiseMaxAttempts || !_host.HasRequestId) return;
if (_lastAppraiseAt != 0 && now - _lastAppraiseAt < AppraiseRetryMs) return;
_appraiseAttempts++;
_lastAppraiseAt = now;
_host.RequestId(uid);
}
/// <summary>Polls the pet's health, then hands the server's health stream back to the fight target.</summary>
private void TickPetHealth(long now, int combatTargetId)
{
if (!_host.HasQueryHealth || now - _lastPetHealthAt < PetHealthPollMs) return;
_lastPetHealthAt = now;
_host.QueryHealth(unchecked((uint)_petId));
uint restore = combatTargetId != 0 ? unchecked((uint)combatTargetId) : 0;
if (restore == 0 && _host.HasGetSelectedItemId) restore = _host.GetSelectedItemId();
if (restore != 0 && restore != unchecked((uint)_petId)) _host.QueryHealth(restore);
}
}

View file

@ -0,0 +1,442 @@
// #region License
// /*
// Microsoft Public License (Ms-PL)
// MonoGame - Copyright © 2009 The MonoGame Team
//
// All rights reserved.
//
// This license governs use of the accompanying software. If you use the software, you accept this license. If you do not
// accept the license, do not use the software.
//
// 1. Definitions
// The terms "reproduce," "reproduction," "derivative works," and "distribution" have the same meaning here as under
// U.S. copyright law.
//
// A "contribution" is the original software, or any additions or changes to the software.
// A "contributor" is any person that distributes its contribution under this license.
// "Licensed patents" are a contributor's patent claims that read directly on its contribution.
//
// 2. Grant of Rights
// (A) Copyright Grant- Subject to the terms of this license, including the license conditions and limitations in section 3,
// each contributor grants you a non-exclusive, worldwide, royalty-free copyright license to reproduce its contribution, prepare derivative works of its contribution, and distribute its contribution or any derivative works that you create.
// (B) Patent Grant- Subject to the terms of this license, including the license conditions and limitations in section 3,
// each contributor grants you a non-exclusive, worldwide, royalty-free license under its licensed patents to make, have made, use, sell, offer for sale, import, and/or otherwise dispose of its contribution in the software or derivative works of the contribution in the software.
//
// 3. Conditions and Limitations
// (A) No Trademark License- This license does not grant you rights to use any contributors' name, logo, or trademarks.
// (B) If you bring a patent claim against any contributor over patents that you claim are infringed by the software,
// your patent license from such contributor to the software ends automatically.
// (C) If you distribute any portion of the software, you must retain all copyright, patent, trademark, and attribution
// notices that are present in the software.
// (D) If you distribute any portion of the software in source code form, you may do so only under this license by including
// a complete copy of this license with your distribution. If you distribute any portion of the software in compiled or object
// code form, you may only do so under a license that complies with this license.
// (E) The software is licensed "as-is." You bear the risk of using it. The contributors give no express warranties, guarantees
// or conditions. You may have additional consumer rights under your local laws which this license cannot change. To the extent
// permitted under your local laws, the contributors exclude the implied warranties of merchantability, fitness for a particular
// purpose and non-infringement.
// */
// #endregion License
//
namespace RynthCore.Plugin.RynthAi.Huds
{
using System.IO;
internal static class DxtUtil
{
internal static byte[] DecompressDxt1(byte[] imageData, int width, int height)
{
using (MemoryStream imageStream = new MemoryStream(imageData))
return DecompressDxt1(imageStream, width, height);
}
internal static byte[] DecompressDxt1(Stream imageStream, int width, int height)
{
byte[] imageData = new byte[width * height * 4];
using (BinaryReader imageReader = new BinaryReader(imageStream))
{
int blockCountX = (width + 3) / 4;
int blockCountY = (height + 3) / 4;
for (int y = 0; y < blockCountY; y++)
{
for (int x = 0; x < blockCountX; x++)
{
DecompressDxt1Block(imageReader, x, y, blockCountX, width, height, imageData);
}
}
}
return imageData;
}
private static void DecompressDxt1Block(BinaryReader imageReader, int x, int y, int blockCountX, int width, int height, byte[] imageData)
{
ushort c0 = imageReader.ReadUInt16();
ushort c1 = imageReader.ReadUInt16();
byte r0, g0, b0;
byte r1, g1, b1;
ConvertRgb565ToRgb888(c0, out r0, out g0, out b0);
ConvertRgb565ToRgb888(c1, out r1, out g1, out b1);
uint lookupTable = imageReader.ReadUInt32();
for (int blockY = 0; blockY < 4; blockY++)
{
for (int blockX = 0; blockX < 4; blockX++)
{
byte r = 0, g = 0, b = 0, a = 255;
uint index = (lookupTable >> 2 * (4 * blockY + blockX)) & 0x03;
if (c0 > c1)
{
switch (index)
{
case 0:
r = r0;
g = g0;
b = b0;
break;
case 1:
r = r1;
g = g1;
b = b1;
break;
case 2:
r = (byte)((2 * r0 + r1) / 3);
g = (byte)((2 * g0 + g1) / 3);
b = (byte)((2 * b0 + b1) / 3);
break;
case 3:
r = (byte)((r0 + 2 * r1) / 3);
g = (byte)((g0 + 2 * g1) / 3);
b = (byte)((b0 + 2 * b1) / 3);
break;
}
}
else
{
switch (index)
{
case 0:
r = r0;
g = g0;
b = b0;
break;
case 1:
r = r1;
g = g1;
b = b1;
break;
case 2:
r = (byte)((r0 + r1) / 2);
g = (byte)((g0 + g1) / 2);
b = (byte)((b0 + b1) / 2);
break;
case 3:
r = 0;
g = 0;
b = 0;
a = 0;
break;
}
}
int px = (x << 2) + blockX;
int py = (y << 2) + blockY;
if ((px < width) && (py < height))
{
int offset = ((py * width) + px) << 2;
imageData[offset] = r;
imageData[offset + 1] = g;
imageData[offset + 2] = b;
imageData[offset + 3] = a;
}
}
}
}
internal static byte[] DecompressDxt3(byte[] imageData, int width, int height)
{
using (MemoryStream imageStream = new MemoryStream(imageData))
return DecompressDxt3(imageStream, width, height);
}
internal static byte[] DecompressDxt3(Stream imageStream, int width, int height)
{
byte[] imageData = new byte[width * height * 4];
using (BinaryReader imageReader = new BinaryReader(imageStream))
{
int blockCountX = (width + 3) / 4;
int blockCountY = (height + 3) / 4;
for (int y = 0; y < blockCountY; y++)
{
for (int x = 0; x < blockCountX; x++)
{
DecompressDxt3Block(imageReader, x, y, blockCountX, width, height, imageData);
}
}
}
return imageData;
}
private static void DecompressDxt3Block(BinaryReader imageReader, int x, int y, int blockCountX, int width, int height, byte[] imageData)
{
byte a0 = imageReader.ReadByte();
byte a1 = imageReader.ReadByte();
byte a2 = imageReader.ReadByte();
byte a3 = imageReader.ReadByte();
byte a4 = imageReader.ReadByte();
byte a5 = imageReader.ReadByte();
byte a6 = imageReader.ReadByte();
byte a7 = imageReader.ReadByte();
ushort c0 = imageReader.ReadUInt16();
ushort c1 = imageReader.ReadUInt16();
byte r0, g0, b0;
byte r1, g1, b1;
ConvertRgb565ToRgb888(c0, out r0, out g0, out b0);
ConvertRgb565ToRgb888(c1, out r1, out g1, out b1);
uint lookupTable = imageReader.ReadUInt32();
int alphaIndex = 0;
for (int blockY = 0; blockY < 4; blockY++)
{
for (int blockX = 0; blockX < 4; blockX++)
{
byte r = 0, g = 0, b = 0, a = 0;
uint index = (lookupTable >> 2 * (4 * blockY + blockX)) & 0x03;
switch (alphaIndex)
{
case 0:
a = (byte)((a0 & 0x0F) | ((a0 & 0x0F) << 4));
break;
case 1:
a = (byte)((a0 & 0xF0) | ((a0 & 0xF0) >> 4));
break;
case 2:
a = (byte)((a1 & 0x0F) | ((a1 & 0x0F) << 4));
break;
case 3:
a = (byte)((a1 & 0xF0) | ((a1 & 0xF0) >> 4));
break;
case 4:
a = (byte)((a2 & 0x0F) | ((a2 & 0x0F) << 4));
break;
case 5:
a = (byte)((a2 & 0xF0) | ((a2 & 0xF0) >> 4));
break;
case 6:
a = (byte)((a3 & 0x0F) | ((a3 & 0x0F) << 4));
break;
case 7:
a = (byte)((a3 & 0xF0) | ((a3 & 0xF0) >> 4));
break;
case 8:
a = (byte)((a4 & 0x0F) | ((a4 & 0x0F) << 4));
break;
case 9:
a = (byte)((a4 & 0xF0) | ((a4 & 0xF0) >> 4));
break;
case 10:
a = (byte)((a5 & 0x0F) | ((a5 & 0x0F) << 4));
break;
case 11:
a = (byte)((a5 & 0xF0) | ((a5 & 0xF0) >> 4));
break;
case 12:
a = (byte)((a6 & 0x0F) | ((a6 & 0x0F) << 4));
break;
case 13:
a = (byte)((a6 & 0xF0) | ((a6 & 0xF0) >> 4));
break;
case 14:
a = (byte)((a7 & 0x0F) | ((a7 & 0x0F) << 4));
break;
case 15:
a = (byte)((a7 & 0xF0) | ((a7 & 0xF0) >> 4));
break;
}
++alphaIndex;
switch (index)
{
case 0:
r = r0;
g = g0;
b = b0;
break;
case 1:
r = r1;
g = g1;
b = b1;
break;
case 2:
r = (byte)((2 * r0 + r1) / 3);
g = (byte)((2 * g0 + g1) / 3);
b = (byte)((2 * b0 + b1) / 3);
break;
case 3:
r = (byte)((r0 + 2 * r1) / 3);
g = (byte)((g0 + 2 * g1) / 3);
b = (byte)((b0 + 2 * b1) / 3);
break;
}
int px = (x << 2) + blockX;
int py = (y << 2) + blockY;
if ((px < width) && (py < height))
{
int offset = ((py * width) + px) << 2;
imageData[offset] = r;
imageData[offset + 1] = g;
imageData[offset + 2] = b;
imageData[offset + 3] = a;
}
}
}
}
internal static byte[] DecompressDxt5(byte[] imageData, int width, int height)
{
using (MemoryStream imageStream = new MemoryStream(imageData))
return DecompressDxt5(imageStream, width, height);
}
internal static byte[] DecompressDxt5(Stream imageStream, int width, int height)
{
byte[] imageData = new byte[width * height * 4];
using (BinaryReader imageReader = new BinaryReader(imageStream))
{
int blockCountX = (width + 3) / 4;
int blockCountY = (height + 3) / 4;
for (int y = 0; y < blockCountY; y++)
{
for (int x = 0; x < blockCountX; x++)
{
DecompressDxt5Block(imageReader, x, y, blockCountX, width, height, imageData);
}
}
}
return imageData;
}
private static void DecompressDxt5Block(BinaryReader imageReader, int x, int y, int blockCountX, int width, int height, byte[] imageData)
{
byte alpha0 = imageReader.ReadByte();
byte alpha1 = imageReader.ReadByte();
ulong alphaMask = (ulong)imageReader.ReadByte();
alphaMask += (ulong)imageReader.ReadByte() << 8;
alphaMask += (ulong)imageReader.ReadByte() << 16;
alphaMask += (ulong)imageReader.ReadByte() << 24;
alphaMask += (ulong)imageReader.ReadByte() << 32;
alphaMask += (ulong)imageReader.ReadByte() << 40;
ushort c0 = imageReader.ReadUInt16();
ushort c1 = imageReader.ReadUInt16();
byte r0, g0, b0;
byte r1, g1, b1;
ConvertRgb565ToRgb888(c0, out r0, out g0, out b0);
ConvertRgb565ToRgb888(c1, out r1, out g1, out b1);
uint lookupTable = imageReader.ReadUInt32();
for (int blockY = 0; blockY < 4; blockY++)
{
for (int blockX = 0; blockX < 4; blockX++)
{
byte r = 0, g = 0, b = 0, a = 255;
uint index = (lookupTable >> 2 * (4 * blockY + blockX)) & 0x03;
uint alphaIndex = (uint)((alphaMask >> 3 * (4 * blockY + blockX)) & 0x07);
if (alphaIndex == 0)
{
a = alpha0;
}
else if (alphaIndex == 1)
{
a = alpha1;
}
else if (alpha0 > alpha1)
{
a = (byte)(((8 - alphaIndex) * alpha0 + (alphaIndex - 1) * alpha1) / 7);
}
else if (alphaIndex == 6)
{
a = 0;
}
else if (alphaIndex == 7)
{
a = 0xff;
}
else
{
a = (byte)(((6 - alphaIndex) * alpha0 + (alphaIndex - 1) * alpha1) / 5);
}
switch (index)
{
case 0:
r = r0;
g = g0;
b = b0;
break;
case 1:
r = r1;
g = g1;
b = b1;
break;
case 2:
r = (byte)((2 * r0 + r1) / 3);
g = (byte)((2 * g0 + g1) / 3);
b = (byte)((2 * b0 + b1) / 3);
break;
case 3:
r = (byte)((r0 + 2 * r1) / 3);
g = (byte)((g0 + 2 * g1) / 3);
b = (byte)((b0 + 2 * b1) / 3);
break;
}
int px = (x << 2) + blockX;
int py = (y << 2) + blockY;
if ((px < width) && (py < height))
{
int offset = ((py * width) + px) << 2;
imageData[offset] = r;
imageData[offset + 1] = g;
imageData[offset + 2] = b;
imageData[offset + 3] = a;
}
}
}
}
private static void ConvertRgb565ToRgb888(ushort color, out byte r, out byte g, out byte b)
{
int temp;
temp = (color >> 11) * 255 + 16;
r = (byte)((temp / 32 + temp) / 32);
temp = ((color & 0x07E0) >> 5) * 255 + 32;
g = (byte)((temp / 64 + temp) / 64);
temp = (color & 0x001F) * 255 + 16;
b = (byte)((temp / 32 + temp) / 32);
}
}
}

View file

@ -0,0 +1,579 @@
// HudController.cs — Owner of RynthAi's floating HUD windows.
//
// * Pack item count HUD (ItemCountHud): icon + carried count for pinned items.
// * Mini Remote (MiniRemoteHud): session stats, attack target, summon (health / time
// left, fed by CombatHudTracker), 30 quick-use item slots, macro toggles, bank balances
// and rebuff buttons.
// * Inventory HUDs setup window (HudSetupUi): picks what the two HUDs show. Opened from
// the Inventory Management settings (ImGui Advanced Settings, the Avalonia Settings
// panel) or "/ra huds".
// * The same Mini Remote inside the engine's RynthAi dashboard (its Mini Remote drawer,
// RynthPluginRenderEmbed "miniremote") and inside the engine's Mini Remote window
// ("miniremote-window"): RenderEmbedded. Data polling runs while any of them shows it
// (MiniRemoteActive); the floating window stays hidden while the engine's window shows it
// (MiniRemoteInEngineWindow), so there is one Mini Remote on screen.
// Every HUD is an ordinary ImGui window, so it can be docked into / undocked from other
// ImGui windows and dragged outside the game window (multi-viewport).
//
// Threading: host reads and every game action run on the pump thread (Tick / posted
// actions). The render thread only reads the published pack snapshot and toggles simple
// flags; list edits are posted so the pump thread is the only writer.
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using RynthCore.Plugin.RynthAi.IltHub;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthAi.Huds;
/// <summary>One carried item name, aggregated over every stack in the pack.</summary>
internal sealed record HudPackRow(string Name, uint Wcid, uint IconDid, long Count, int FirstId);
/// <summary>Immutable pack view published by the pump thread.</summary>
internal sealed class HudPackSnapshot
{
public static readonly HudPackSnapshot Empty = new(Array.Empty<HudPackRow>());
public HudPackRow[] Rows { get; }
public Dictionary<string, HudPackRow> ByName { get; }
public HudPackSnapshot(HudPackRow[] rows)
{
Rows = rows;
ByName = new Dictionary<string, HudPackRow>(StringComparer.OrdinalIgnoreCase);
foreach (var r in rows) ByName[r.Name] = r;
}
public long CountOf(string name) => ByName.TryGetValue(name, out var r) ? r.Count : 0;
}
internal sealed class HudController
{
private const uint StypeIcon = 8; // DataID Icon → PWD _iconID
private const int StypeStackSize = 12;
private const long PackScanIntervalMs = 1000;
private const long SaveIntervalMs = 5000;
private readonly RynthCoreHost _host;
private readonly Func<WorldObjectCache?> _cache;
private readonly HudStore _store;
private readonly ConcurrentQueue<Action> _posted = new();
private readonly Dictionary<int, uint> _iconById = new();
private readonly ItemCountHud _itemHud;
private readonly MiniRemoteHud _miniRemote;
private readonly HudSetupUi _setup;
private readonly CombatHudTracker _combat;
private volatile HudPackSnapshot _pack = HudPackSnapshot.Empty;
private long _lastScanAt;
private long _lastSaveAt;
private bool _scanRequested;
/// <summary>
/// How long a pack item the player selected stays assignable after the game selection moves
/// on (the combat bot re-selects monsters, so "the selected item" is often gone by the time
/// the player clicks a slot).
/// </summary>
private const long RememberSelectionMs = 120_000;
private uint _lastSeenSelection;
private int _lastPackSelId;
private long _lastPackSelAt;
private volatile string _assignCandidate = string.Empty;
public HudController(RynthCoreHost host, string charFolder, Func<WorldObjectCache?> cache,
LegacyDashboardRenderer dashboard, Func<IltHubController?> hub, HudIconCache icons, Func<int> attackTargetId)
{
_host = host;
_cache = cache;
_store = new HudStore(charFolder);
State = _store.Load();
Icons = icons;
Dashboard = dashboard;
Hub = hub;
_itemHud = new ItemCountHud(this);
_miniRemote = new MiniRemoteHud(this);
_setup = new HudSetupUi(this);
_combat = new CombatHudTracker(host, cache, attackTargetId);
}
public HudState State { get; }
public HudIconCache Icons { get; }
public LegacyDashboardRenderer Dashboard { get; }
public Func<IltHubController?> Hub { get; }
public RynthCoreHost Host => _host;
/// <summary>The Mini Remote's session stats (the same SessionStats code as RynthTracker); null if it failed to start.</summary>
public RynthCore.Plugin.Shared.SessionStatsTracker? SessionStats { get; init; }
/// <summary>Latest pack view (render thread safe).</summary>
public HudPackSnapshot Pack => _pack;
/// <summary>Latest attack target / summon view (render thread safe).</summary>
public CombatHudSnapshot Combat => _combat.Snapshot;
/// <summary>
/// Name of the pack item a slot click would assign (current or remembered selection); empty
/// when there is none. Render thread safe.
/// </summary>
public string AssignCandidate => _assignCandidate;
/// <summary>Chat translator views for the Mini Remote row; null until the translator exists.</summary>
public RynthCore.Plugin.RynthAi.Translate.TranslateUi? Translate { get; set; }
/// <summary>Queues work for the next pump tick (safe from the render thread).</summary>
public void Post(Action action) => _posted.Enqueue(action);
/// <summary>
/// Runs a RynthCore "/rc ..." command through the engine's chat dispatcher on the next pump
/// tick (any thread). Says so in chat when this RynthCore can't run it.
/// </summary>
public void RunEngineCommand(string command)
{
if (string.IsNullOrWhiteSpace(command)) return;
Post(() =>
{
if (_host.HasInvokeChatParser && _host.InvokeChatParser(command)) return;
Chat($"[Mini Remote] {command} needs RynthCore's ImGui layer; type it in chat to see why.");
});
}
private static long NowMs => Environment.TickCount64;
/// <summary>
/// How long after its last frame in the RynthAi dashboard's Mini Remote drawer the remote
/// still counts as on screen (the drawer draws every frame while it is out).
/// </summary>
private const long EmbeddedVisibleMs = 1500;
/// <summary>When the Mini Remote last drew in an engine surface (TickCount64); written on the render thread.</summary>
private long _embeddedDrawnAt = long.MinValue / 2;
/// <summary>When the engine's Mini Remote window last drew it (TickCount64); written on the render thread.</summary>
private long _windowDrawnAt = long.MinValue / 2;
/// <summary>The Mini Remote is on screen: the floating window or an engine surface. Any thread.</summary>
public bool MiniRemoteActive =>
State.ShowMiniRemote || NowMs - System.Threading.Interlocked.Read(ref _embeddedDrawnAt) < EmbeddedVisibleMs;
/// <summary>
/// The engine's Mini Remote window is showing the remote: the floating copy stays hidden
/// meanwhile, so there is one Mini Remote on screen. Any thread.
/// </summary>
public bool MiniRemoteInEngineWindow =>
NowMs - System.Threading.Interlocked.Read(ref _windowDrawnAt) < EmbeddedVisibleMs;
// ── Pump thread ─────────────────────────────────────────────────────────
public void Tick()
{
int guard = 0;
while (guard++ < 64 && _posted.TryDequeue(out var a))
{
try { a(); }
catch (Exception ex) { RynthLog.Exception(LogCat.Huds, ex, "posted HUD action"); }
}
long now = NowMs;
// The pack is only scanned while something shows it.
bool remote = MiniRemoteActive;
bool needPack = State.ShowItemHud || remote || State.ShowSetup;
if (needPack && (_scanRequested || now - _lastScanAt >= PackScanIntervalMs))
{
_scanRequested = false;
_lastScanAt = now;
RebuildPack();
}
Icons.Tick();
if (needPack) TrackPackSelection(now);
// Target / summon polling sends health queries and appraisals, so it only runs while shown.
if (remote && (State.MiniShowTarget || State.MiniShowPet))
_combat.Tick();
if (now - _lastSaveAt >= SaveIntervalMs)
{
_lastSaveAt = now;
_store.SaveIfDirty(State);
}
}
public void OnLogout()
{
_store.SaveIfDirty(State);
_pack = HudPackSnapshot.Empty;
_iconById.Clear();
_combat.OnLogout();
}
/// <summary>Aggregates the pack by item name and refreshes pinned entries' icon / WCID.</summary>
private void RebuildPack()
{
var cache = _cache();
if (cache == null) return;
var byName = new Dictionary<string, HudPackRow>(StringComparer.OrdinalIgnoreCase);
var seen = new HashSet<int>();
foreach (var wo in cache.GetInventory())
{
if (wo == null || string.IsNullOrWhiteSpace(wo.Name)) continue;
seen.Add(wo.Id);
long count = Math.Max(1, wo.Values(StypeStackSize, 1));
if (byName.TryGetValue(wo.Name, out var row))
{
byName[wo.Name] = row with { Count = row.Count + count };
continue;
}
byName[wo.Name] = new HudPackRow(wo.Name, Wcid(wo), IconOf(wo), count, wo.Id);
}
// Forget icon lookups for items that left the pack.
if (_iconById.Count > seen.Count + 64)
foreach (int id in _iconById.Keys.Where(k => !seen.Contains(k)).ToList()) _iconById.Remove(id);
var snap = new HudPackSnapshot(byName.Values.OrderBy(r => r.Name, StringComparer.OrdinalIgnoreCase).ToArray());
_pack = snap;
// Remember icon / WCID on pinned entries so they still draw while none are carried.
foreach (var e in State.ItemHudItems.Concat(State.MiniRemoteSlots))
{
if (e.IsEmpty || !snap.ByName.TryGetValue(e.Name, out var r)) continue;
if (r.IconDid != 0) e.IconDid = r.IconDid;
if (r.Wcid != 0) e.Wcid = r.Wcid;
}
}
private uint IconOf(WorldObject wo)
{
if (_iconById.TryGetValue(wo.Id, out uint icon) && icon != 0) return icon;
if (_host.HasGetObjectDataIdProperty && _host.TryGetObjectDataIdProperty(unchecked((uint)wo.Id), StypeIcon, out icon))
_iconById[wo.Id] = icon;
return icon;
}
private uint Wcid(WorldObject wo)
=> _host.HasGetObjectWcid && _host.TryGetObjectWcid(unchecked((uint)wo.Id), out uint w) ? w : 0;
// ── Actions (pump thread; post them from the render thread) ──────────────
/// <summary>Rescans the pack on the next tick.</summary>
public void RequestScan() => _scanRequested = true;
/// <summary>Uses one carried item by name (falls back to WCID when the name changed).</summary>
public void UseItem(HudItemEntry entry)
{
if (entry.IsEmpty) return;
var cache = _cache();
if (cache == null || !_host.HasUseObject) return;
var inv = cache.GetInventory().Where(w => w != null).ToList();
var wo = inv.FirstOrDefault(w => w.Name.Equals(entry.Name, StringComparison.OrdinalIgnoreCase))
?? (entry.Wcid != 0 ? inv.FirstOrDefault(w => Wcid(w) == entry.Wcid) : null);
if (wo == null) { Chat($"[RynthAi] No {entry.Name} in your pack."); return; }
_host.UseObject(unchecked((uint)wo.Id));
RynthLog.Trace(LogCat.Huds, $"use {wo.Name} (0x{wo.Id:X8})");
}
/// <summary>Carried item by object id, or null.</summary>
private WorldObject? PackItem(int id)
=> id == 0 ? null : _cache()?.GetInventory().FirstOrDefault(w => w != null && w.Id == id);
/// <summary>
/// Remembers the last pack item selected in the game (native inventory, or the RynthCore
/// Inventory window, which mirrors its clicks to the game selection). Only re-checks the
/// pack when the selection changes.
/// </summary>
private void TrackPackSelection(long now)
{
if (!_host.HasGetSelectedItemId) return;
uint sel = _host.GetSelectedItemId();
if (sel != _lastSeenSelection)
{
_lastSeenSelection = sel;
var wo = PackItem(unchecked((int)sel));
if (wo != null)
{
_lastPackSelId = wo.Id;
_lastPackSelAt = now;
}
}
// The candidate label only feeds tooltips / menus: refresh it a few times a second.
if (now - _lastCandidateAt < 250) return;
_lastCandidateAt = now;
var candidate = AssignablePackItem(quiet: true);
_assignCandidate = candidate?.Name ?? string.Empty;
}
private long _lastCandidateAt;
/// <summary>
/// The pack item to assign: the current game selection when it is carried, otherwise the
/// last carried item the player selected within <see cref="RememberSelectionMs"/>.
/// </summary>
private WorldObject? AssignablePackItem(bool quiet = false)
{
if (!_host.HasGetSelectedItemId)
{
if (!quiet) Chat("[RynthAi] This client build can't read the selected item.");
return null;
}
uint selected = _host.GetSelectedItemId();
var wo = PackItem(unchecked((int)selected));
bool fellBack = false;
long rememberedAge = NowMs - _lastPackSelAt;
if (wo == null && _lastPackSelId != 0 && rememberedAge <= RememberSelectionMs)
{
wo = PackItem(_lastPackSelId);
fellBack = wo != null;
}
// Quiet calls feed tooltips several times a second: only real assignments are traced.
if (!quiet)
{
string selInfo = selected == 0 ? "none" : $"0x{selected:X8} ({(fellBack || wo == null ? DescribeCacheEntry(unchecked((int)selected)) : "in inventory")})";
string result = wo == null ? "nothing to assign"
: fellBack ? $"fell back to remembered 0x{_lastPackSelId:X8} '{wo.Name}' ({rememberedAge / 1000.0:0.0} s old)"
: $"selected '{wo.Name}'";
RynthLog.Trace(LogCat.Huds, $"assign candidate: selected={selInfo}; {result}");
}
if (wo == null && !quiet)
Chat("[RynthAi] Click an item in your pack (game inventory or RynthCore Inventory) first, "
+ "or drag it from the RynthCore Inventory onto the slot.");
return wo;
}
/// <summary>The item to act on for "use the selected item" HUD actions.</summary>
private WorldObject? SelectedPackItem() => AssignablePackItem();
public void AddSelectedToItemHud()
{
var wo = SelectedPackItem();
if (wo != null) AddToItemHud(wo.Name);
}
public void AddToItemHud(string name)
{
if (string.IsNullOrWhiteSpace(name) || State.ItemHudItems.Any(e => e.Name.Equals(name, StringComparison.OrdinalIgnoreCase))) return;
var row = _pack.ByName.TryGetValue(name, out var r) ? r : null;
State.ItemHudItems.Add(new HudItemEntry { Name = name, Wcid = row?.Wcid ?? 0, IconDid = row?.IconDid ?? 0 });
RynthLog.Trace(LogCat.Huds, $"item HUD += '{name}' (first id 0x{(uint)(row?.FirstId ?? 0):X8}, wcid {row?.Wcid ?? 0}, in pack scan: {(row != null ? "yes" : "no")})");
}
/// <summary>
/// Adds <paramref name="name"/> to the item count HUD (if missing) and shows the HUD.
/// Icon and WCID fill in on the next pack scan. Returns the chat confirmation.
/// </summary>
public string AddToItemHudAndShow(string name)
{
name = name.Trim();
bool already = State.ItemHudItems.Any(e => e.Name.Equals(name, StringComparison.OrdinalIgnoreCase));
if (!already) AddToItemHud(name);
State.ShowItemHud = true;
RequestScan();
return already ? $"{name} is already on the item count HUD." : $"Added {name} to the item count HUD.";
}
public void RemoveFromItemHud(string name)
=> State.ItemHudItems.RemoveAll(e => e.Name.Equals(name, StringComparison.OrdinalIgnoreCase));
/// <summary>Moves a HUD entry up (-1) or down (+1) in display order.</summary>
public void MoveItemHudEntry(string name, int delta)
{
var list = State.ItemHudItems;
int i = list.FindIndex(e => e.Name.Equals(name, StringComparison.OrdinalIgnoreCase));
int j = i + delta;
if (i < 0 || j < 0 || j >= list.Count) return;
(list[i], list[j]) = (list[j], list[i]);
}
/// <summary>Removes HUD entries for items no longer carried.</summary>
public void DropMissingFromItemHud()
{
var pack = _pack;
int n = State.ItemHudItems.RemoveAll(e => pack.CountOf(e.Name) == 0);
Chat(n > 0 ? $"[RynthAi] Removed {n} item(s) you no longer carry from the HUD." : "[RynthAi] Every HUD item is still in your pack.");
}
/// <summary>Puts the selected (or last selected) pack item into Mini Remote slot <paramref name="slot"/>.</summary>
public void SetSlotFromSelection(int slot)
{
if (slot < 0 || slot >= State.MiniRemoteSlots.Count) return;
var wo = AssignablePackItem();
if (wo != null) AssignSlot(slot, wo);
}
/// <summary>
/// Puts carried item <paramref name="objectId"/> into <paramref name="slot"/> (-1 = first empty
/// slot). Used by drag-and-drop from the RynthCore Inventory and its "Add to Mini Remote" menu.
/// </summary>
public void SetSlotFromItemId(int slot, uint objectId)
{
var wo = PackItem(unchecked((int)objectId));
if (wo == null)
{
// The cache's view of the id shows a classification miss (item filed outside inventory).
int invCount = _cache()?.GetInventory().Count() ?? -1;
RynthLog.Trace(LogCat.Huds, $"slot-from-id: 0x{objectId:X8} not in inventory ({invCount} items); {DescribeCacheEntry(unchecked((int)objectId))}");
Chat("[RynthAi] That item is no longer in your pack.");
return;
}
RynthLog.Trace(LogCat.Huds, $"slot-from-id: 0x{objectId:X8} = '{wo.Name}' ({wo.ObjectClass}), requested slot {(slot < 0 ? "first empty" : (slot + 1).ToString("00"))}");
if (slot < 0) slot = State.MiniRemoteSlots.FindIndex(e => e.IsEmpty);
if (slot < 0) { Chat("[RynthAi] Every Mini Remote slot is in use. Clear one first (right-click it)."); return; }
if (slot >= State.MiniRemoteSlots.Count) return;
AssignSlot(slot, wo);
}
private void AssignSlot(int slot, WorldObject wo)
{
var row = _pack.ByName.TryGetValue(wo.Name, out var r) ? r : null;
var entry = new HudItemEntry { Name = wo.Name, Wcid = row?.Wcid ?? Wcid(wo), IconDid = row?.IconDid ?? IconOf(wo) };
State.MiniRemoteSlots[slot] = entry;
RynthLog.Trace(LogCat.Huds, $"assign slot {slot + 1:00} = '{wo.Name}' 0x{(uint)wo.Id:X8} (wcid {entry.Wcid}, icon 0x{entry.IconDid:X8})");
Chat($"[RynthAi] Mini Remote slot {slot + 1:00} = {wo.Name}.");
}
/// <summary>How the world cache knows <paramref name="id"/> (for traces): name and class, or that it doesn't.</summary>
private string DescribeCacheEntry(int id)
{
var cache = _cache();
if (cache == null) return "no world cache";
var wo = cache[id];
return wo == null ? "unknown to the world cache" : $"world cache has '{wo.Name}' as {wo.ObjectClass}";
}
/// <summary>
/// Remote command "remoteslot &lt;slot|first&gt; &lt;objectId&gt;" (RynthCore Inventory menu).
/// Slot is 1-based. Returns false when the value can't be parsed.
/// </summary>
public bool HandleRemoteSlot(string value)
{
var parts = (value ?? string.Empty).Split(' ', StringSplitOptions.RemoveEmptyEntries);
int slot = 0;
bool ok = parts.Length == 2 && uint.TryParse(parts[1], out _);
if (ok)
{
if (parts[0].Equals("first", StringComparison.OrdinalIgnoreCase)) slot = -1;
else if (int.TryParse(parts[0], out int n) && n >= 1) slot = n - 1;
else ok = false;
}
if (!ok)
{
RynthLog.Trace(LogCat.Huds, $"remoteslot '{value}': can't parse (expected '<slot|first> <objectId>')");
return false;
}
uint id = uint.Parse(parts[1]);
RynthLog.Trace(LogCat.Huds, $"remoteslot '{value}': slot {(slot < 0 ? "first empty" : (slot + 1).ToString("00"))}, id 0x{id:X8}");
SetSlotFromItemId(slot, id);
return true;
}
public void ClearSlot(int slot)
{
if (slot >= 0 && slot < State.MiniRemoteSlots.Count) State.MiniRemoteSlots[slot] = new HudItemEntry();
}
public void Chat(string text)
{
// Every message the player sees also lands in the Huds trace.
RynthLog.Trace(LogCat.Huds, "chat: " + text);
if (_host.HasWriteToChat) _host.WriteToChat(text, 1);
}
/// <summary>
/// "/ra huds|itemhud|remote [show|hide|toggle]" and the matching remote command.
/// Returns the chat confirmation.
/// </summary>
public string HandleCommand(string which, string mode)
{
static bool Resolve(string m, bool current) => m.ToLowerInvariant() switch
{
"show" or "on" or "true" or "1" => true,
"hide" or "off" or "false" or "0" => false,
_ => !current,
};
switch (which)
{
case "itemhud":
State.ShowItemHud = Resolve(mode, State.ShowItemHud);
return State.ShowItemHud ? "Pack item count HUD shown." : "Pack item count HUD hidden.";
case "remote":
case "miniremote":
State.ShowMiniRemote = Resolve(mode, State.ShowMiniRemote);
if (State.ShowMiniRemote && MiniRemoteInEngineWindow)
return "The Mini Remote is open in RynthCore's Mini Remote window (bar button, /rc miniremote); the floating copy stays hidden while that window is open.";
return State.ShowMiniRemote ? "Mini Remote shown." : "Mini Remote hidden.";
default:
State.ShowSetup = Resolve(mode, State.ShowSetup);
return State.ShowSetup ? "Inventory HUDs window shown." : "Inventory HUDs window hidden.";
}
}
/// <summary>
/// Puts the Mini Remote on tab <paramref name="tab"/> ("" = the remote itself, else an ILT tab
/// id). Modes: "show" selects it and shows the Mini Remote (the floating one, unless RynthCore's
/// window hosts it); "hide" goes back to the remote tab when this tab is the one selected;
/// "toggle" does whichever undoes the current state; "select" only switches tabs (RynthCore's
/// dashboard opens its own window). Any thread: plain field writes the next frame applies.
/// Returns the chat reply.
/// </summary>
public string HandleTabCommand(string tab, string mode)
{
tab ??= string.Empty;
string label = tab.Length == 0 ? "Remote" : char.ToUpperInvariant(tab[0]) + tab.Substring(1);
bool selected = string.Equals(State.MiniRemoteTab, tab, StringComparison.OrdinalIgnoreCase);
string m = (mode ?? string.Empty).ToLowerInvariant();
bool hide = m is "hide" or "off" or "close"
|| (m is not ("show" or "on" or "open" or "select") && selected && MiniRemoteActive);
if (hide)
{
if (selected) _miniRemote.RequestTab(string.Empty);
return selected ? $"Mini Remote back on its Remote tab ({label} closed)." : $"The {label} tab isn't the one showing.";
}
_miniRemote.RequestTab(tab);
if (m == "select") return $"Mini Remote: {label} tab.";
if (!MiniRemoteActive && !MiniRemoteInEngineWindow) State.ShowMiniRemote = true;
return MiniRemoteInEngineWindow
? $"Mini Remote (RynthCore's window): {label} tab."
: $"Mini Remote shown on its {label} tab.";
}
// ── Render thread ───────────────────────────────────────────────────────
public void Render()
{
int pushed = LegacyDashboardRenderer.PushDashboardStyle();
try
{
if (State.ShowSetup) _setup.Render();
if (State.ShowItemHud) _itemHud.Render(); else _itemHud.OnHidden();
// The engine's Mini Remote window hosts the same remote: draw one, not two.
if (State.ShowMiniRemote && !MiniRemoteInEngineWindow) _miniRemote.Render(); else _miniRemote.OnHidden();
}
finally
{
ImGuiNET.ImGui.PopStyleColor(pushed);
}
}
/// <summary>
/// Draws the Mini Remote into the engine's current ImGui window (the RynthAi dashboard's
/// Mini Remote drawer, or with <paramref name="window"/> the engine's Mini Remote window)
/// and returns the content size it wants. Render thread.
/// </summary>
public System.Numerics.Vector2 RenderEmbedded(bool window = false)
{
long now = NowMs;
System.Threading.Interlocked.Exchange(ref _embeddedDrawnAt, now);
if (window) System.Threading.Interlocked.Exchange(ref _windowDrawnAt, now);
int pushed = LegacyDashboardRenderer.PushDashboardStyle();
try
{
return _miniRemote.RenderEmbedded(window);
}
finally
{
ImGuiNET.ImGui.PopStyleColor(pushed);
}
}
}

View file

@ -0,0 +1,56 @@
// HudDraw.cs — Small ImGui drawing helpers shared by the HUD windows (render thread only).
using System;
using System.Numerics;
using ImGuiNET;
namespace RynthCore.Plugin.RynthAi.Huds;
internal static class HudDraw
{
private static readonly Vector4 Opaque = new(1f, 1f, 1f, 1f);
private static readonly Vector4 Faded = new(1f, 1f, 1f, 0.35f);
private static readonly Vector4 NoBorder = Vector4.Zero;
/// <summary>
/// Draws an item icon of <paramref name="size"/> pixels. While the texture is still
/// loading (or the item has no icon) a framed box with the name's first letter stands in.
/// <paramref name="dim"/> fades it (e.g. none carried).
/// </summary>
public static void Icon(HudIconCache icons, uint iconDid, string name, float size, bool dim)
{
IntPtr tex = icons.GetTexture(iconDid);
var sz = new Vector2(size, size);
if (tex != IntPtr.Zero)
{
ImGui.Image(tex, sz, Vector2.Zero, Vector2.One, dim ? Faded : Opaque, NoBorder);
return;
}
Placeholder(name, sz, dim);
}
/// <summary>Framed stand-in with the item's first letter, same footprint as an icon.</summary>
public static void Placeholder(string name, Vector2 size, bool dim)
{
Vector2 p = ImGui.GetCursorScreenPos();
ImGui.Dummy(size);
var dl = ImGui.GetWindowDrawList();
uint frame = ImGui.GetColorU32(new Vector4(0.45f, 0.55f, 0.65f, dim ? 0.35f : 0.8f));
uint fill = ImGui.GetColorU32(new Vector4(0.12f, 0.16f, 0.22f, dim ? 0.35f : 0.8f));
dl.AddRectFilled(p, p + size, fill, 3f);
dl.AddRect(p, p + size, frame, 3f);
if (string.IsNullOrEmpty(name)) return;
string letter = name.Substring(0, 1).ToUpperInvariant();
Vector2 ts = ImGui.CalcTextSize(letter);
dl.AddText(p + (size - ts) * 0.5f, ImGui.GetColorU32(new Vector4(0.9f, 0.9f, 0.9f, dim ? 0.4f : 1f)), letter);
}
/// <summary>"1468", "12.3k", "4.5m", "1.2b" — compact counts for tight HUD rows.</summary>
public static string Compact(double v)
{
double a = Math.Abs(v);
if (a >= 1e9) return (v / 1e9).ToString("0.0") + "b";
if (a >= 1e6) return (v / 1e6).ToString("0.0") + "m";
if (a >= 1e4) return (v / 1e3).ToString("0.0") + "k";
return v.ToString("0");
}
}

View file

@ -0,0 +1,266 @@
// HudIconCache.cs — Item icons for the RynthAi HUD windows.
//
// An item's icon DID (PWD _iconID, 0x06xxxxxx) points at a Texture file in portal.dat.
// Decoding (dat read + pixel conversion) runs on the pump thread; the D3D9 texture is
// created lazily on the render thread, a few per frame, so a full pack never stalls a frame.
// Textures are POOL_MANAGED (they survive device resets) and are never released: plugin
// unload can run off the render thread, where touching the device is unsafe, and the
// whole set is a few hundred 32×32 icons.
using System;
using System.Collections.Concurrent;
using System.IO;
using System.Runtime.InteropServices;
using RynthCore.Plugin.RynthAi.Raycasting;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthAi.Huds;
internal sealed class HudIconCache
{
// IDirect3DDevice9 / IDirect3DTexture9 vtable slots.
private const int VtCreateTexture = 23;
private const int VtLockRect = 19;
private const int VtUnlockRect = 20;
private const int VtRelease = 2;
private const uint D3DFMT_A8R8G8B8 = 21;
private const uint D3DPOOL_MANAGED = 1;
/// <summary>Texture uploads allowed per rendered frame.</summary>
private const int UploadsPerFrame = 6;
/// <summary>Icons decoded per pump tick.</summary>
private const int DecodesPerTick = 12;
/// <summary>Runaway guard; a full character's icons are a few hundred.</summary>
private const int MaxIcons = 4000;
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate int CreateTextureD(IntPtr dev, uint w, uint h, uint levels, uint usage, uint fmt, uint pool, out IntPtr tex, IntPtr shared);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate int LockRectD(IntPtr tex, uint level, ref D3DLockedRect locked, IntPtr rect, uint flags);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate int UnlockRectD(IntPtr tex, uint level);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate uint ReleaseD(IntPtr obj);
[StructLayout(LayoutKind.Sequential)]
private struct D3DLockedRect { public int Pitch; public IntPtr Bits; }
/// <summary>Decoded icon in D3D A8R8G8B8 order (A&lt;&lt;24 | R&lt;&lt;16 | G&lt;&lt;8 | B).</summary>
private sealed class Decoded
{
public int Width;
public int Height;
public uint[] Pixels = Array.Empty<uint>();
}
private readonly RynthCoreHost _host;
private readonly Func<DatDatabase?> _portal;
// DID → decoded pixels (null value = decode failed, don't retry).
private readonly ConcurrentDictionary<uint, Decoded?> _decoded = new();
// DIDs the render thread asked for that the pump thread hasn't decoded yet.
private readonly ConcurrentQueue<uint> _pending = new();
private readonly ConcurrentDictionary<uint, byte> _queued = new();
// Render thread only.
private readonly System.Collections.Generic.Dictionary<uint, IntPtr> _textures = new();
private IntPtr _textureDevice;
private int _uploadFrame = -1;
private int _uploadsThisFrame;
public HudIconCache(RynthCoreHost host, Func<DatDatabase?> portal)
{
_host = host;
_portal = portal;
}
// ── Render thread ───────────────────────────────────────────────────────
/// <summary>
/// ImGui texture id for <paramref name="iconDid"/>, or IntPtr.Zero while it is still
/// being decoded / uploaded (callers draw a placeholder).
/// </summary>
public IntPtr GetTexture(uint iconDid)
{
if (iconDid == 0) return IntPtr.Zero;
IntPtr device = _host.D3DDevice;
if (device == IntPtr.Zero) return IntPtr.Zero;
// A new device means the old textures belong to a dead device; forget them (not
// Release — the owning device may already be gone).
if (device != _textureDevice)
{
_textures.Clear();
_textureDevice = device;
}
if (_textures.TryGetValue(iconDid, out IntPtr tex)) return tex;
if (!_decoded.TryGetValue(iconDid, out Decoded? d))
{
if (_queued.TryAdd(iconDid, 0)) _pending.Enqueue(iconDid);
return IntPtr.Zero;
}
if (d == null) return IntPtr.Zero;
int frame = ImGuiNET.ImGui.GetFrameCount();
if (frame != _uploadFrame) { _uploadFrame = frame; _uploadsThisFrame = 0; }
if (_uploadsThisFrame >= UploadsPerFrame) return IntPtr.Zero;
_uploadsThisFrame++;
tex = Upload(device, d);
// Failed uploads are remembered as Zero so they aren't retried every frame.
_textures[iconDid] = tex;
return tex;
}
// ── Pump thread ─────────────────────────────────────────────────────────
/// <summary>Decodes a batch of requested icons (dat reads stay off the render thread).</summary>
public void Tick()
{
var portal = _portal();
if (portal == null || !portal.IsLoaded) return;
for (int i = 0; i < DecodesPerTick && _pending.TryDequeue(out uint did); i++)
{
_queued.TryRemove(did, out _);
if (_decoded.Count >= MaxIcons) { _decoded.TryAdd(did, null); continue; }
Decoded? d = null;
try { d = Decode(portal, did); }
catch (Exception ex) { RynthLog.Exception(LogCat.Huds, ex, $"icon decode 0x{did:X8}"); }
_decoded[did] = d;
}
}
// ── Decoding (Texture 0x06 → ARGB) ──────────────────────────────────────
// Texture layout: Id(u32) Unknown(i32) Width(i32) Height(i32) Format(u32) Length(i32)
// Source[Length], then DefaultPaletteId(u32) for INDEX16 / P8.
private static Decoded? Decode(DatDatabase portal, uint textureId)
{
byte[]? data = portal.GetFileData(textureId);
if (data == null || data.Length < 24) return null;
using var ms = new MemoryStream(data);
using var r = new BinaryReader(ms);
r.ReadUInt32(); r.ReadInt32();
int w = r.ReadInt32(), h = r.ReadInt32();
uint fmt = r.ReadUInt32();
int len = r.ReadInt32();
if (w <= 0 || h <= 0 || w > 1024 || h > 1024 || len < 0 || ms.Position + len > ms.Length) return null;
byte[] src = r.ReadBytes(len);
uint palId = 0;
if ((fmt == 101 || fmt == 41) && ms.Position + 4 <= ms.Length) palId = r.ReadUInt32();
var px = new uint[w * h];
static uint Argb(int a, int rr, int g, int b) => ((uint)a << 24) | ((uint)rr << 16) | ((uint)g << 8) | (uint)b;
switch (fmt)
{
case 827611204: return FromRgba(DxtUtil.DecompressDxt1(src, w, h), w, h); // DXT1
case 861165636: return FromRgba(DxtUtil.DecompressDxt3(src, w, h), w, h); // DXT3
case 894720068: return FromRgba(DxtUtil.DecompressDxt5(src, w, h), w, h); // DXT5
case 20: // R8G8B8, stored B,G,R
for (int i = 0; i < px.Length && i * 3 + 2 < src.Length; i++) px[i] = Argb(255, src[i * 3 + 2], src[i * 3 + 1], src[i * 3]);
break;
case 21: // A8R8G8B8, stored B,G,R,A
case 22: // X8R8G8B8
for (int i = 0; i < px.Length && i * 4 + 3 < src.Length; i++)
px[i] = Argb(fmt == 22 ? 255 : src[i * 4 + 3], src[i * 4 + 2], src[i * 4 + 1], src[i * 4]);
break;
case 23: // R5G6B5
for (int i = 0; i < px.Length && i * 2 + 1 < src.Length; i++)
{
int v = src[i * 2] | (src[i * 2 + 1] << 8);
px[i] = Argb(255, ((v >> 11) & 0x1F) << 3, ((v >> 5) & 0x3F) << 2, (v & 0x1F) << 3);
}
break;
case 26: // A4R4G4B4
for (int i = 0; i < px.Length && i * 2 + 1 < src.Length; i++)
{
int v = src[i * 2] | (src[i * 2 + 1] << 8);
px[i] = Argb(((v >> 12) & 0xF) * 17, ((v >> 8) & 0xF) * 17, ((v >> 4) & 0xF) * 17, (v & 0xF) * 17);
}
break;
case 28: // A8 greyscale
for (int i = 0; i < px.Length && i < src.Length; i++) px[i] = Argb(255, src[i], src[i], src[i]);
break;
case 101: // INDEX16
case 41: // P8
{
uint[]? pal = LoadPalette(portal, palId);
if (pal == null || pal.Length == 0) return null;
bool p8 = fmt == 41;
for (int i = 0; i < px.Length; i++)
{
int idx;
if (p8) { if (i >= src.Length) break; idx = src[i]; }
else { if (i * 2 + 1 >= src.Length) break; idx = src[i * 2] | (src[i * 2 + 1] << 8); }
px[i] = pal[idx % pal.Length]; // palette entries are already ARGB
}
break;
}
default:
return null;
}
return new Decoded { Width = w, Height = h, Pixels = px };
}
/// <summary>Palette (0x04): Id(u32), Count(i32), Count × ARGB(u32).</summary>
private static uint[]? LoadPalette(DatDatabase portal, uint paletteId)
{
byte[]? data = portal.GetFileData(paletteId);
if (data == null || data.Length < 8) return null;
int n = BitConverter.ToInt32(data, 4);
if (n <= 0 || n > 65536) return null;
n = Math.Min(n, (data.Length - 8) / 4);
var pal = new uint[n];
for (int i = 0; i < n; i++) pal[i] = BitConverter.ToUInt32(data, 8 + i * 4);
return pal;
}
/// <summary>DxtUtil output (R,G,B,A bytes) → ARGB.</summary>
private static Decoded FromRgba(byte[] rgba, int w, int h)
{
var px = new uint[w * h];
for (int i = 0; i < px.Length && i * 4 + 3 < rgba.Length; i++)
px[i] = ((uint)rgba[i * 4 + 3] << 24) | ((uint)rgba[i * 4] << 16) | ((uint)rgba[i * 4 + 1] << 8) | rgba[i * 4 + 2];
return new Decoded { Width = w, Height = h, Pixels = px };
}
// ── D3D9 upload (render thread) ─────────────────────────────────────────
private static unsafe IntPtr Upload(IntPtr device, Decoded d)
{
try
{
int hr = Vt<CreateTextureD>(device, VtCreateTexture)(device, (uint)d.Width, (uint)d.Height, 1, 0,
D3DFMT_A8R8G8B8, D3DPOOL_MANAGED, out IntPtr tex, IntPtr.Zero);
if (hr < 0 || tex == IntPtr.Zero) return IntPtr.Zero;
var locked = new D3DLockedRect();
if (Vt<LockRectD>(tex, VtLockRect)(tex, 0, ref locked, IntPtr.Zero, 0) < 0)
{
Vt<ReleaseD>(tex, VtRelease)(tex);
return IntPtr.Zero;
}
// Row by row: the locked pitch can be wider than Width * 4.
for (int row = 0; row < d.Height; row++)
{
fixed (uint* src = &d.Pixels[row * d.Width])
Buffer.MemoryCopy(src, (void*)IntPtr.Add(locked.Bits, row * locked.Pitch), d.Width * 4, d.Width * 4);
}
Vt<UnlockRectD>(tex, VtUnlockRect)(tex, 0);
return tex;
}
catch (Exception ex)
{
RynthLog.Exception(LogCat.Huds, ex, "icon upload");
return IntPtr.Zero;
}
}
private static unsafe T Vt<T>(IntPtr obj, int index) where T : Delegate
{
void** vt = *(void***)obj;
return Marshal.GetDelegateForFunctionPointer<T>((IntPtr)vt[index]);
}
}

View file

@ -0,0 +1,183 @@
// HudSetupUi.cs — "Inventory HUDs" setup window (UtilityBelt Item Hud tab equivalent).
//
// * Show / hide the pack item count HUD and the Mini Remote.
// * Two lists: items on the HUD (left) and carried items not on it (right).
// "<" pins the highlighted right row, ">" unpins the highlighted left row,
// Up / Down reorder the HUD. "Add from inventory" pins the item selected in the game.
// * Mini Remote slots: pick a slot, then Set (selected game item) or Clear.
// Render thread only; list edits are posted to the pump thread.
using System;
using System.Linq;
using System.Numerics;
using ImGuiNET;
using RynthCore.Plugin.RynthAi.LegacyUi;
namespace RynthCore.Plugin.RynthAi.Huds;
internal sealed class HudSetupUi
{
private const float ListIcon = 18f;
private readonly HudController _hud;
private string _selOnHud = string.Empty;
private string _selInPack = string.Empty;
private string _packFilter = string.Empty;
private int _slot;
public HudSetupUi(HudController hud) => _hud = hud;
public void Render()
{
var s = _hud.State;
ImGui.SetNextWindowSize(new Vector2(640, 520), ImGuiCond.FirstUseEver);
bool open = true;
bool visible = ImGui.Begin("Inventory HUDs##rynthhudsetup", ref open);
if (!open) s.ShowSetup = false;
if (!visible) { ImGui.End(); return; }
RenderHudToggles(s);
ImGui.Separator();
RenderItemLists(s);
ImGui.Separator();
RenderSlotPicker(s);
ImGui.End();
}
private static void RenderHudToggles(HudState s)
{
bool itemHud = s.ShowItemHud;
if (ImGui.Checkbox("Show pack item count HUD", ref itemHud)) s.ShowItemHud = itemHud;
ImGui.SameLine();
bool names = s.ItemHudShowNames;
if (ImGui.Checkbox("with names", ref names)) s.ItemHudShowNames = names;
ImGui.SameLine();
bool remote = s.ShowMiniRemote;
if (ImGui.Checkbox("Show Mini Remote", ref remote)) s.ShowMiniRemote = remote;
ImGui.TextDisabled("Both are separate windows: drag them anywhere, dock them into other RynthAi windows,");
ImGui.TextDisabled("or pull them outside the game window. Right-click a HUD for its options.");
}
private void RenderItemLists(HudState s)
{
ImGui.TextWrapped("Left = shown on the HUD. Right = in your pack but not on the HUD. "
+ "< pins the highlighted right row; > removes the highlighted left row. "
+ "Add from inventory uses the item selected in the game.");
if (ImGui.Button("Scan pack")) _hud.Post(_hud.RequestScan);
ImGui.SameLine();
if (ImGui.Button("Add from inventory")) _hud.Post(_hud.AddSelectedToItemHud);
ImGui.SameLine();
if (ImGui.Button("Drop missing")) _hud.Post(_hud.DropMissingFromItemHud);
if (ImGui.IsItemHovered()) ImGui.SetTooltip("Remove HUD items you no longer carry.");
var entries = s.ItemHudItems.ToArray();
var pack = _hud.Pack;
float listH = 230f;
float colW = Math.Max(180f, (ImGui.GetContentRegionAvail().X - 50f) * 0.5f);
// ── Left: on the HUD ──
ImGui.BeginGroup();
ImGui.TextUnformatted($"On HUD ({entries.Length})");
if (ImGui.BeginChild("##hudon", new Vector2(colW, listH), ImGuiChildFlags.Borders))
{
foreach (var e in entries)
{
long count = pack.CountOf(e.Name);
if (Row(e.Name, e.IconDid, $"{e.Name} | {count:N0}", _selOnHud == e.Name, count == 0))
_selOnHud = e.Name;
}
}
ImGui.EndChild();
bool haveLeft = entries.Any(e => e.Name == _selOnHud);
ImGui.BeginDisabled(!haveLeft);
string upName = _selOnHud;
if (ImGui.SmallButton("Up")) _hud.Post(() => _hud.MoveItemHudEntry(upName, -1));
ImGui.SameLine();
if (ImGui.SmallButton("Down")) _hud.Post(() => _hud.MoveItemHudEntry(upName, +1));
ImGui.EndDisabled();
ImGui.EndGroup();
// ── Middle: move buttons ──
ImGui.SameLine();
ImGui.BeginGroup();
ImGui.Dummy(new Vector2(1, listH * 0.35f));
ImGui.BeginDisabled(string.IsNullOrEmpty(_selInPack));
string add = _selInPack;
if (ImGui.Button("<", new Vector2(36, 0))) { _hud.Post(() => _hud.AddToItemHud(add)); _selInPack = string.Empty; }
ImGui.EndDisabled();
ImGui.BeginDisabled(!haveLeft);
string remove = _selOnHud;
if (ImGui.Button(">", new Vector2(36, 0))) { _hud.Post(() => _hud.RemoveFromItemHud(remove)); _selOnHud = string.Empty; }
ImGui.EndDisabled();
ImGui.EndGroup();
// ── Right: in pack, not on the HUD ──
ImGui.SameLine();
ImGui.BeginGroup();
ImGui.TextUnformatted("Not on HUD");
ImGui.SameLine();
ImGui.SetNextItemWidth(Math.Max(80f, colW - 90f));
ImGui.InputTextWithHint("##hudpackfilter", "filter", ref _packFilter, 64u);
if (ImGui.BeginChild("##hudoff", new Vector2(colW, listH), ImGuiChildFlags.Borders))
{
var pinned = entries.Select(e => e.Name).ToHashSet(StringComparer.OrdinalIgnoreCase);
foreach (var r in pack.Rows)
{
if (pinned.Contains(r.Name)) continue;
if (_packFilter.Length > 0 && !r.Name.Contains(_packFilter, StringComparison.OrdinalIgnoreCase)) continue;
if (Row(r.Name, r.IconDid, $"{r.Name} | {r.Count:N0}", _selInPack == r.Name, false))
_selInPack = r.Name;
// Double-click pins straight away.
if (ImGui.IsItemHovered() && ImGui.IsMouseDoubleClicked(ImGuiMouseButton.Left))
{
string name = r.Name;
_hud.Post(() => _hud.AddToItemHud(name));
}
}
if (pack.Rows.Length == 0) ImGui.TextDisabled("Scanning your pack...");
}
ImGui.EndChild();
ImGui.EndGroup();
}
/// <summary>Icon + label selectable row; returns true when clicked.</summary>
private bool Row(string name, uint iconDid, string label, bool selected, bool dim)
{
Vector2 start = ImGui.GetCursorPos();
bool clicked = ImGui.Selectable($"##row{name}", selected, ImGuiSelectableFlags.AllowOverlap, new Vector2(0, ListIcon));
ImGui.SetCursorPos(start);
HudDraw.Icon(_hud.Icons, iconDid, name, ListIcon, dim);
ImGui.SameLine();
if (dim) ImGui.TextDisabled(label);
else ImGui.TextUnformatted(label);
return clicked;
}
private void RenderSlotPicker(HudState s)
{
var slots = s.MiniRemoteSlots.ToArray();
if (slots.Length == 0) return;
ImGui.TextColored(LegacyDashboardRenderer.ColTeal, "Mini Remote slots");
ImGui.TextDisabled($"Slot 01 = top-left of the Mini Remote grid ({HudState.MiniRemoteColumns} per row). "
+ "Select an item in your pack, pick the slot, then Set.");
_slot = Math.Clamp(_slot, 0, slots.Length - 1);
string Label(int i) => $"{i + 1:00} - {(slots[i].IsEmpty ? "(empty)" : slots[i].Name)}";
ImGui.SetNextItemWidth(320);
if (ImGui.BeginCombo("##mrslot", Label(_slot)))
{
for (int i = 0; i < slots.Length; i++)
if (ImGui.Selectable(Label(i), i == _slot)) _slot = i;
ImGui.EndCombo();
}
int slot = _slot;
ImGui.SameLine();
if (ImGui.Button("Set")) _hud.Post(() => _hud.SetSlotFromSelection(slot));
ImGui.SameLine();
ImGui.BeginDisabled(slots[slot].IsEmpty);
if (ImGui.Button("Clear")) _hud.Post(() => _hud.ClearSlot(slot));
ImGui.EndDisabled();
ImGui.SameLine();
if (ImGui.Button("Refresh")) _hud.Post(_hud.RequestScan);
}
}

View file

@ -0,0 +1,136 @@
// HudState.cs — Persisted per-character settings for the floating HUD windows
// (<charFolder>\huds.json). Fields, not properties, so the source-generated
// RynthAiJsonContext (IncludeFields) round-trips them under NativeAOT.
using System;
using System.Collections.Generic;
using System.IO;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace RynthCore.Plugin.RynthAi.Huds;
public sealed class HudState
{
/// <summary>Mini Remote gem grid size (UB layout: 5 columns × 6 rows).</summary>
public const int MiniRemoteColumns = 5;
public const int MiniRemoteSlotCount = 30;
/// <summary>Mini Remote slot icon edge in pixels: the grow / shrink range and the default.</summary>
public const float MinMiniRemoteSlotSize = 18f, MaxMiniRemoteSlotSize = 64f, DefaultMiniRemoteSlotSize = 28f;
/// <summary>The "Inventory HUDs" setup window is open.</summary>
public bool ShowSetup;
// ── Pack item count HUD ──
public bool ShowItemHud;
public bool ItemHudShowNames;
public bool ItemHudLocked;
public float ItemHudIconSize = 20f;
/// <summary>Items shown on the HUD, in display order (matched by name).</summary>
public List<HudItemEntry> ItemHudItems = new();
// ── Mini Remote ──
public bool ShowMiniRemote;
public bool MiniRemoteLocked;
/// <summary>Sections laid out side by side in columns (the V/H button) instead of stacked.</summary>
public bool MiniRemoteHorizontal;
public bool MiniShowStats = true;
/// <summary>Attack target row: name, health bar, distance.</summary>
public bool MiniShowTarget = true;
/// <summary>Pet row: the summon that is out (health, time left), else the next combat essence.</summary>
public bool MiniShowPet = true;
public bool MiniShowGems = true;
public bool MiniShowToggles = true;
public bool MiniShowBank = true;
public bool MiniShowRebuff = true;
/// <summary>Chat translator row: on/off, receive / send language swap.</summary>
public bool MiniShowTranslate = true;
/// <summary>Temple guardian row: the last riddle answer with a Give button (only while one is recent).</summary>
public bool MiniShowGuardian = true;
/// <summary>Gem grid slots, row-major from the top-left (empty Name = unassigned).</summary>
public List<HudItemEntry> MiniRemoteSlots = new();
/// <summary>
/// Slot icon edge in pixels (Ctrl+wheel over the slots, or Options > Slot size).
/// Clamped to <see cref="MinMiniRemoteSlotSize"/>..<see cref="MaxMiniRemoteSlotSize"/>.
/// </summary>
public float MiniRemoteSlotSize = DefaultMiniRemoteSlotSize;
/// <summary>
/// The Mini Remote's selected tab: "" for the remote itself, else an ILT tab id
/// (IltSections.TabId: character, quests, pets, banking, gear, charms, games).
/// </summary>
public string MiniRemoteTab = string.Empty;
}
/// <summary>An item pinned to a HUD. Matched by name; Wcid / IconDid are remembered so the
/// entry still shows its icon while none are carried.</summary>
public sealed class HudItemEntry
{
public string Name = string.Empty;
public uint Wcid;
public uint IconDid;
[JsonIgnore] public bool IsEmpty => string.IsNullOrWhiteSpace(Name);
}
/// <summary>Loads / dirty-checked saves of <see cref="HudState"/>.</summary>
internal sealed class HudStore
{
private readonly string _charFolder;
private string _lastJson = string.Empty;
public HudStore(string charFolder) => _charFolder = charFolder ?? string.Empty;
private string StatePath => Path.Combine(_charFolder, "huds.json");
public HudState Load()
{
HudState? s = null;
try
{
if (_charFolder.Length > 0 && File.Exists(StatePath))
{
string json = File.ReadAllText(StatePath);
s = JsonSerializer.Deserialize(json, RynthAiJsonContext.Default.HudState);
if (s != null) _lastJson = json;
}
}
catch (Exception ex) { RynthLog.Exception(LogCat.Huds, ex, $"load {StatePath}"); }
s ??= new HudState();
Normalize(s);
return s;
}
/// <summary>Writes the state only when its JSON differs from the last write.</summary>
public void SaveIfDirty(HudState state)
{
if (_charFolder.Length == 0) return;
try
{
string json = JsonSerializer.Serialize(state, RynthAiJsonContext.Default.HudState);
if (json == _lastJson) return;
Directory.CreateDirectory(_charFolder);
string tmp = StatePath + ".tmp";
File.WriteAllText(tmp, json);
File.Move(tmp, StatePath, overwrite: true);
_lastJson = json;
}
catch (Exception ex) { RynthLog.Exception(LogCat.Huds, ex, $"save {StatePath}"); }
}
/// <summary>Repairs null lists / out-of-range values after deserialization.</summary>
private static void Normalize(HudState s)
{
s.ItemHudItems ??= new();
s.ItemHudItems.RemoveAll(e => e == null || e.IsEmpty);
s.ItemHudIconSize = Math.Clamp(s.ItemHudIconSize, 12f, 48f);
s.MiniRemoteSlots ??= new();
for (int i = 0; i < s.MiniRemoteSlots.Count; i++) s.MiniRemoteSlots[i] ??= new HudItemEntry();
while (s.MiniRemoteSlots.Count < HudState.MiniRemoteSlotCount) s.MiniRemoteSlots.Add(new HudItemEntry());
if (s.MiniRemoteSlots.Count > HudState.MiniRemoteSlotCount)
s.MiniRemoteSlots.RemoveRange(HudState.MiniRemoteSlotCount, s.MiniRemoteSlots.Count - HudState.MiniRemoteSlotCount);
s.MiniRemoteTab ??= string.Empty;
// A huds.json from before the setting has no value (0): use the default.
s.MiniRemoteSlotSize = s.MiniRemoteSlotSize <= 0f || float.IsNaN(s.MiniRemoteSlotSize)
? HudState.DefaultMiniRemoteSlotSize
: Math.Clamp(s.MiniRemoteSlotSize, HudState.MinMiniRemoteSlotSize, HudState.MaxMiniRemoteSlotSize);
}
}

View file

@ -0,0 +1,89 @@
// ItemCountHud.cs — Floating "pack item count" HUD: one row per pinned item with its
// icon, carried count and (optionally) name. Right-click for options. Render thread only.
using System.Linq;
using System.Numerics;
using ImGuiNET;
namespace RynthCore.Plugin.RynthAi.Huds;
internal sealed class ItemCountHud
{
private const string OptionsPopup = "##itemhudopts";
private static readonly Vector4 ColCount = new(0.95f, 0.95f, 0.95f, 1f);
private static readonly Vector4 ColNone = new(0.95f, 0.45f, 0.40f, 1f);
private static readonly Vector4 ColName = new(0.70f, 0.75f, 0.80f, 1f);
private readonly HudController _hud;
private bool _rescueChecked; // off-screen check done for the current show
public ItemCountHud(HudController hud) => _hud = hud;
/// <summary>The HUD was not drawn this frame: check its position again on the next show.</summary>
public void OnHidden() => _rescueChecked = false;
public void Render()
{
var s = _hud.State;
var entries = s.ItemHudItems.ToArray();
var pack = _hud.Pack;
var flags = ImGuiWindowFlags.NoTitleBar | ImGuiWindowFlags.AlwaysAutoResize | ImGuiWindowFlags.NoScrollbar
| ImGuiWindowFlags.NoFocusOnAppearing | ImGuiWindowFlags.NoNav;
if (s.ItemHudLocked) flags |= ImGuiWindowFlags.NoMove;
// Right of and above centre, clear of the character in the middle of the view.
UiPlacement.CenterFirstUse(new Vector2(220, -160));
ImGui.SetNextWindowBgAlpha(0.55f);
ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(4, 4));
ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, new Vector2(4, 2));
bool visible = ImGui.Begin("Item HUD##rynthitemhud", flags);
ImGui.PopStyleVar(2);
if (!visible) { ImGui.End(); return; }
UiPlacement.RescueOncePerShow(ref _rescueChecked);
if (entries.Length == 0)
{
ImGui.TextDisabled("Item HUD is empty.");
ImGui.TextDisabled("Right-click > Edit items...");
}
float size = s.ItemHudIconSize;
foreach (var e in entries)
{
long count = pack.CountOf(e.Name);
HudDraw.Icon(_hud.Icons, e.IconDid, e.Name, size, count == 0);
if (ImGui.IsItemHovered()) ImGui.SetTooltip($"{e.Name}\n{count:N0} carried");
ImGui.SameLine();
// Vertically centre the text on the icon.
float pad = (size - ImGui.GetTextLineHeight()) * 0.5f;
if (pad > 0) ImGui.SetCursorPosY(ImGui.GetCursorPosY() + pad);
ImGui.TextColored(count == 0 ? ColNone : ColCount, count.ToString("N0"));
if (s.ItemHudShowNames)
{
ImGui.SameLine();
ImGui.TextColored(ColName, e.Name);
}
}
if (ImGui.IsWindowHovered() && ImGui.IsMouseReleased(ImGuiMouseButton.Right)) ImGui.OpenPopup(OptionsPopup);
RenderOptions(s);
ImGui.End();
}
private void RenderOptions(HudState s)
{
if (!ImGui.BeginPopup(OptionsPopup)) return;
ImGui.TextDisabled("Item HUD");
bool names = s.ItemHudShowNames;
if (ImGui.Checkbox("Show names", ref names)) s.ItemHudShowNames = names;
bool locked = s.ItemHudLocked;
if (ImGui.Checkbox("Lock position", ref locked)) s.ItemHudLocked = locked;
float size = s.ItemHudIconSize;
ImGui.SetNextItemWidth(120);
if (ImGui.SliderFloat("Icon size", ref size, 12f, 48f, "%.0f")) s.ItemHudIconSize = size;
ImGui.Separator();
if (ImGui.MenuItem("Edit items...")) s.ShowSetup = true;
if (ImGui.MenuItem("Hide HUD")) s.ShowItemHud = false;
ImGui.EndPopup();
}
}

View file

@ -0,0 +1,953 @@
// MiniRemoteHud.cs — The Mini Remote (UtilityBelt-style) for RynthAi. Render thread only.
//
// One window with tabs: Remote (the sections below), the universal tabs Quests and Pets (every
// world), and on ILT worlds the ILT tabs Character, Banking, Gear and Games (IltHubUi draws
// their bodies; an ILT tab shows once the server reports its feature on). The tab bar's
// selection is saved (HudState.MiniRemoteTab) and "/ra hub open <section>" or RynthCore's
// dashboard switch it (RequestTab). The Guardian (ILT only) and Bounties are RynthCore ILT
// panels (the bar's ILT button).
// Right-click on the remote: "Character" (Spells, Quests, Pets, Skills, Inventory, Item Count,
// Inventory HUDs: windows every server has), then "Server: <name>", i.e. the installed server
// plugins' windows for the world you're on, which RynthCore sends (ServerMenuModel), or "Treat
// this world as ..." when none matches. The Options button holds the Mini Remote's own settings.
// The V/H button stacks the sections (vertical) or lays them out in three columns (horizontal).
//
// Remote sections (each can be hidden from the Options menu):
// Stats session time and per-hour XP / luminance / kills / coins / pyreals (ILT rates)
// Target the creature combat is attacking: name, health bar, distance
// Pet the summon that is out (health bar, time left), else the next combat essence and
// whether it is ready
// Slots 5 × 6 quick-use item grid; click uses the item (an empty slot takes the selected
// pack item), right-click assigns / clears, and items dragged from the game's
// inventory or the RynthCore Inventory window drop straight into a slot. Ctrl+wheel
// over the grid (or Options > Slot size) grows / shrinks the boxes.
// Toggles macro and subsystem switches (same as the dashboard buttons; not in the drawer)
// Bank ILT bank balances (pyreals, luminance, keys, coins)
// Rebuff force rebuff / cancel rebuff
// Translate chat translator on/off and the receive <-> send language swap
// Guardian the last Temple guardian answer with a Give button (only while it is recent)
// All game actions are posted to the pump thread.
//
// RenderEmbedded draws the same sections and Options menu inside the engine's RynthAi dashboard
// (its Mini Remote drawer, opened by the Hub launcher's right-click or the drawer tab) and
// reports the size it wants; the drawer is sized from that. The drawer leaves out Toggles (the
// dashboard it sits on already has those switches) and the tabs (it is too narrow for them).
// RenderEmbedded(window: true) draws it in the engine's Mini Remote window instead (bar button,
// /rc miniremote): tabs and Toggles included, and the floating window stays hidden meanwhile
// (HudController), so that window is the one Mini Remote.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
using System.Threading;
using ImGuiNET;
using RynthCore.Plugin.RynthAi.IltHub;
using RynthCore.Plugin.RynthAi.LegacyUi;
namespace RynthCore.Plugin.RynthAi.Huds;
internal sealed class MiniRemoteHud
{
private const string OptionsPopup = "##miniremoteopts";
private const string MenuPopup = "##miniremotemenu";
private const string SlotPopup = "##miniremoteslot";
/// <summary>Pixels per Ctrl+wheel notch over the slot grid.</summary>
private const float SlotSizeStep = 2f;
/// <summary>Narrowest horizontal-layout column (fits the stat lines and the translate row).</summary>
private const float MinColumnWidth = 190f;
private const float HeaderButtonWidth = 80f;
private static readonly Vector4 ColLabel = new(0.80f, 0.84f, 0.90f, 1f);
private static readonly Vector4 ColReady = new(0.40f, 0.95f, 0.45f, 1f);
private static readonly Vector4 ColOut = new(0.45f, 0.85f, 0.95f, 1f);
private static readonly Vector4 ColEmpty = new(0.95f, 0.45f, 0.40f, 1f);
private static readonly Vector4 ColBusy = new(0.95f, 0.80f, 0.35f, 1f);
private readonly HudController _hud;
private int _slotMenuIndex = -1;
private bool _rescueChecked; // off-screen check done for the current show
private bool _columnOpen; // horizontal layout: a column was already started this frame (next one goes SameLine)
private bool _embedded; // true only inside RenderEmbedded (an engine surface)
private bool _inWindow; // with _embedded: the engine's Mini Remote window, not the dashboard drawer
// A tab switch asked for by a command or the engine (any thread), applied by the next tab bar;
// null = none. Starts as the saved tab so the first tab bar restores it.
private string? _pendingTab;
private bool _pendingTabFromState = true;
// This frame's tab bar showed the Remote tab (right-click Options belongs to it only).
private bool _onRemoteTab = true;
// The Options button was clicked this frame (the popup opens at window level).
private bool _openOptions;
// The ILT tabs offered this frame (reused, so a frame doesn't allocate).
private readonly List<IltSection> _tabs = new();
public MiniRemoteHud(HudController hud) => _hud = hud;
/// <summary>The remote was not drawn this frame: check its position again on the next show.</summary>
public void OnHidden() => _rescueChecked = false;
/// <summary>
/// Switches to tab <paramref name="tab"/> ("" = the remote, else an ILT tab id) on the next
/// frame the tab bar draws. Any thread.
/// </summary>
public void RequestTab(string tab)
{
_pendingTabFromState = false;
Volatile.Write(ref _pendingTab, tab ?? string.Empty);
}
public void Render()
{
var s = _hud.State;
var flags = ImGuiWindowFlags.AlwaysAutoResize | ImGuiWindowFlags.NoCollapse | ImGuiWindowFlags.NoScrollbar
| ImGuiWindowFlags.NoFocusOnAppearing;
if (s.MiniRemoteLocked) flags |= ImGuiWindowFlags.NoMove;
// Left of and above centre, mirroring the Item HUD's first spot.
UiPlacement.CenterFirstUse(new Vector2(-220, -160));
ImGui.SetNextWindowBgAlpha(0.70f);
bool open = true;
ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, new Vector2(4, 3));
bool visible = ImGui.Begin("Mini Remote##rynthminiremote", ref open, flags);
ImGui.PopStyleVar();
if (!open) s.ShowMiniRemote = false;
if (!visible) { ImGui.End(); return; }
UiPlacement.RescueOncePerShow(ref _rescueChecked);
RenderBody(s, _hud.Hub(), allowTabs: true);
// Right-click on the remote opens the Character / server menu, unless a slot's own menu is
// open (the ILT tabs have their own right-click menus).
if (_onRemoteTab && _slotMenuIndex < 0 && ImGui.IsWindowHovered(ImGuiHoveredFlags.ChildWindows) && ImGui.IsMouseReleased(ImGuiMouseButton.Right))
ImGui.OpenPopup(MenuPopup);
RenderOptions(s, embedded: false);
RenderMenu(s);
_slotMenuIndex = -1;
ImGui.End();
}
/// <summary>
/// The same sections drawn into the caller's current window (the engine's RynthAi dashboard
/// drawer, or with <paramref name="window"/> the engine's Mini Remote window; both size
/// themselves from the result) instead of a window of their own. Returns the content size it
/// wants: the selected tab's width, and the height drawn.
/// </summary>
public Vector2 RenderEmbedded(bool window = false)
{
var s = _hud.State;
_slotMenuIndex = -1;
_embedded = true;
_inWindow = window;
float startY = ImGui.GetCursorPosY();
ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, new Vector2(4, 3));
try
{
float width = RenderBody(s, _hud.Hub(), allowTabs: !InDrawer);
if (_onRemoteTab && _slotMenuIndex < 0 && ImGui.IsWindowHovered(ImGuiHoveredFlags.ChildWindows) && ImGui.IsMouseReleased(ImGuiMouseButton.Right))
ImGui.OpenPopup(MenuPopup);
RenderOptions(s, embedded: true);
RenderMenu(s);
float height = ImGui.GetCursorPosY() - startY - ImGui.GetStyle().ItemSpacing.Y;
return new Vector2(width, Math.Max(0f, height) + 2f);
}
finally
{
ImGui.PopStyleVar();
_slotMenuIndex = -1;
_embedded = false;
_inWindow = false;
}
}
// ── Tabs ────────────────────────────────────────────────────────────────
/// <summary>
/// The tab bar (when <paramref name="allowTabs"/>: the universal tabs on every world, the ILT
/// tabs on ILT worlds) and the selected tab: the remote, or a tab's body in a child of its
/// fixed size. Returns the width the content wants (never narrower than the tab bar's labels).
/// </summary>
private float RenderBody(HudState s, IltHubController? hub, bool allowTabs)
{
_onRemoteTab = true;
_tabs.Clear();
if (allowTabs && hub != null)
{
foreach (IltSection section in IltSections.Tabs)
if (hub.TabShown(section)) _tabs.Add(section);
}
if (_tabs.Count == 0)
{
RenderRemote(s, hub);
return EmbeddedWidth(s);
}
if (_pendingTabFromState)
{
_pendingTabFromState = false;
Interlocked.CompareExchange(ref _pendingTab, s.MiniRemoteTab ?? string.Empty, null);
}
string? pending = Interlocked.Exchange(ref _pendingTab, null);
float width = TabBarWidth();
_onRemoteTab = false;
if (ImGui.BeginTabBar("##mrtabs", ImGuiTabBarFlags.FittingPolicyScroll | ImGuiTabBarFlags.NoTooltip))
{
if (BeginTab(RemoteTabLabel, TabFlags(IltSections.RemoteTab, pending)))
{
_onRemoteTab = true;
s.MiniRemoteTab = IltSections.RemoteTab;
RenderRemote(s, hub);
width = Math.Max(width, EmbeddedWidth(s));
ImGui.EndTabItem();
}
foreach (IltSection section in _tabs)
{
string id = IltSections.TabId(section);
if (!BeginTab(TabLabels[(int)section], TabFlags(id, pending))) continue;
s.MiniRemoteTab = id;
Vector2 size = IltHubUi.TabSize(section);
// The tab draws into a child of its own size; tables in it scroll inside it.
ImGui.BeginChild(TabBodyIds[(int)section], size, ImGuiChildFlags.None, ImGuiWindowFlags.None);
hub!.RenderTab(section);
ImGui.EndChild();
width = Math.Max(width, size.X);
ImGui.EndTabItem();
}
ImGui.EndTabBar();
}
return width;
}
// Tab labels as NUL-terminated UTF-8 and the tab body child ids, indexed by (int)IltSection,
// built once so the tab bar doesn't allocate per frame.
private static readonly byte[] RemoteTabLabel = Utf8Z("Remote##mrtab");
private static readonly byte[][] TabLabels = BuildPerSection(s => Utf8Z(IltSections.Label(s) + "##mrtab"));
private static readonly string[] TabBodyIds = BuildPerSection(s => "##mrtabbody_" + IltSections.TabId(s));
private static T[] BuildPerSection<T>(Func<IltSection, T> make)
{
var result = new T[(int)IltSection.Guardian + 1];
foreach (IltSection section in IltSections.Tabs) result[(int)section] = make(section);
return result;
}
private static byte[] Utf8Z(string text)
{
byte[] bytes = new byte[System.Text.Encoding.UTF8.GetByteCount(text) + 1];
System.Text.Encoding.UTF8.GetBytes(text, 0, text.Length, bytes, 0);
return bytes;
}
/// <summary>
/// BeginTabItem without a close button: ImGui.NET only wraps the flags overload together with
/// p_open, and a non-null p_open draws an X on the tab.
/// </summary>
private static unsafe bool BeginTab(byte[] labelUtf8Z, ImGuiTabItemFlags flags)
{
fixed (byte* label = labelUtf8Z)
return ImGuiNative.igBeginTabItem(label, null, flags) != 0;
}
/// <summary>SetSelected for the tab a command asked for this frame.</summary>
private static ImGuiTabItemFlags TabFlags(string id, string? pending) =>
pending != null && string.Equals(pending, id, StringComparison.OrdinalIgnoreCase)
? ImGuiTabItemFlags.SetSelected : ImGuiTabItemFlags.None;
/// <summary>Width of every tab label side by side (the embedded window shouldn't be narrower, or tabs scroll).</summary>
private float TabBarWidth()
{
var style = ImGui.GetStyle();
float w = ImGui.CalcTextSize("Remote").X + style.FramePadding.X * 2f;
foreach (IltSection section in _tabs)
w += style.ItemInnerSpacing.X + ImGui.CalcTextSize(IltSections.Label(section)).X + style.FramePadding.X * 2f;
return w;
}
/// <summary>The Remote tab: the [V/H] [Options] row, then the sections in the chosen layout.</summary>
private void RenderRemote(HudState s, IltHubController? hub)
{
RenderHeaderRow(s);
if (s.MiniRemoteHorizontal) RenderHorizontal(s, hub);
else RenderVertical(s, hub);
}
/// <summary>In the dashboard drawer (not the floating window or the engine's Mini Remote window).</summary>
private bool InDrawer => _embedded && !_inWindow;
/// <summary>The Toggles section is drawn: chosen in Options, and never in the dashboard drawer.</summary>
private bool ShowToggles(HudState s) => s.MiniShowToggles && !InDrawer;
/// <summary>
/// The width the sections need: one column stacked, else one per non-empty column side by side.
/// Never measured from what was drawn, since widgets fill the width they are given.
/// </summary>
private float EmbeddedWidth(HudState s)
{
float colW = ColumnWidth(s);
if (!s.MiniRemoteHorizontal) return colW;
int cols = 0;
if (s.MiniShowStats || s.MiniShowTarget || s.MiniShowPet) cols++;
if (s.MiniShowGems || ShowToggles(s)) cols++;
if (s.MiniShowBank || s.MiniShowRebuff || s.MiniShowTranslate || s.MiniShowGuardian) cols++;
cols = Math.Max(1, cols);
return cols * colW + (cols - 1) * ImGui.GetStyle().ItemSpacing.X;
}
// ── Layout ──────────────────────────────────────────────────────────────
/// <summary>[V/H] and [Options] buttons. Fixed widths so the auto-resizing window can't grow from them.</summary>
private void RenderHeaderRow(HudState s)
{
if (ImGui.Button((s.MiniRemoteHorizontal ? "H" : "V") + "##mrlayout", new Vector2(HeaderButtonWidth, 0)))
s.MiniRemoteHorizontal = !s.MiniRemoteHorizontal;
if (ImGui.IsItemHovered())
ImGui.SetTooltip(s.MiniRemoteHorizontal ? "Horizontal: sections in columns. Click to stack them." : "Vertical: sections stacked. Click to lay them out in columns.");
ImGui.SameLine();
// Opened by RenderOptions: this row sits inside the Remote tab, whose ID the popup must not get.
if (ImGui.Button("Options##mropts", new Vector2(HeaderButtonWidth, 0))) _openOptions = true;
if (ImGui.IsItemHovered()) ImGui.SetTooltip("Mini Remote settings: sections, layout, slot size.\nRight-click the remote for the Character and server windows.");
}
private void RenderVertical(HudState s, IltHubController? hub)
{
RenderStatusSections(s, hub);
RenderActionSections(s);
RenderEconomySections(s, hub);
}
/// <summary>
/// Three side-by-side columns: status (stats, target, pet), actions (slots, toggles) and
/// economy (bank, rebuff, translate). Each column is a fixed-width child that grows only in
/// height; widgets sized from the available width would otherwise make the auto-resizing
/// window grow every frame.
/// </summary>
private void RenderHorizontal(HudState s, IltHubController? hub)
{
float colW = ColumnWidth(s);
_columnOpen = false;
if (s.MiniShowStats || s.MiniShowTarget || s.MiniShowPet)
{
BeginColumn("##mrcolstatus", colW);
RenderStatusSections(s, hub);
ImGui.EndChild();
}
if (s.MiniShowGems || ShowToggles(s))
{
BeginColumn("##mrcolactions", colW);
RenderActionSections(s);
ImGui.EndChild();
}
if (s.MiniShowBank || s.MiniShowRebuff || s.MiniShowTranslate || s.MiniShowGuardian)
{
BeginColumn("##mrcoleconomy", colW);
RenderEconomySections(s, hub);
ImGui.EndChild();
}
}
/// <summary>Starts a column child (caller always calls EndChild, whatever BeginChild returned).</summary>
private void BeginColumn(string id, float width)
{
if (_columnOpen) ImGui.SameLine();
_columnOpen = true;
ImGui.BeginChild(id, new Vector2(width, 0), ImGuiChildFlags.AutoResizeY, ImGuiWindowFlags.NoScrollbar);
}
/// <summary>Wide enough for the slot grid at its current size, and never narrower than MinColumnWidth.</summary>
private static float ColumnWidth(HudState s)
{
int cols = HudState.MiniRemoteColumns;
float grid = cols * SlotButtonSize(s) + (cols - 1) * ImGui.GetStyle().ItemSpacing.X;
return Math.Max(MinColumnWidth, grid);
}
/// <summary>Slot icon edge in pixels (the saved size, clamped).</summary>
private static float SlotSize(HudState s) =>
Math.Clamp(s.MiniRemoteSlotSize, HudState.MinMiniRemoteSlotSize, HudState.MaxMiniRemoteSlotSize);
/// <summary>Slot button edge including its 1 px frame padding on each side.</summary>
private static float SlotButtonSize(HudState s) => SlotSize(s) + 2f;
/// <summary>
/// Grows (+) or shrinks (-) the slot boxes within the saved range (huds.json picks it up on
/// the next SaveIfDirty, like every other HUD setting).
/// </summary>
private static void ResizeSlots(HudState s, float delta) =>
s.MiniRemoteSlotSize = Math.Clamp(SlotSize(s) + delta, HudState.MinMiniRemoteSlotSize, HudState.MaxMiniRemoteSlotSize);
private void RenderStatusSections(HudState s, IltHubController? hub)
{
var combat = _hud.Combat;
if (s.MiniShowStats) RenderStats(hub);
if (s.MiniShowTarget) RenderTarget(combat);
if (s.MiniShowPet) RenderPet(hub, combat);
if (s.MiniShowStats) RenderStatButtons(hub);
}
private void RenderActionSections(HudState s)
{
if (s.MiniShowGems) RenderSlots(s);
if (ShowToggles(s)) RenderToggles(_hud.Dashboard.Settings);
}
private void RenderEconomySections(HudState s, IltHubController? hub)
{
if (s.MiniShowBank) RenderBank(hub);
if (s.MiniShowRebuff) RenderRebuff();
if (s.MiniShowTranslate && _hud.Translate is { } translate) translate.RenderHubSection();
if (s.MiniShowGuardian && IltActive(hub)) hub!.Guardian.RenderRemoteLine();
}
// ── Sections ────────────────────────────────────────────────────────────
private static bool IltActive(IltHubController? hub) => hub != null && hub.Options.IsIltLikeWorld;
private static void Stat(string label, string value)
{
ImGui.TextColored(ColLabel, label);
ImGui.SameLine();
ImGui.TextUnformatted(value);
}
/// <summary>
/// Session stats on every world: the shared SessionStats (RynthTracker's code, so these match the
/// Tracker panel), plus ILT coins and pyreals.
/// </summary>
private void RenderStats(IltHubController? hub)
{
var v = _hud.SessionStats?.View ?? RynthCore.Plugin.Shared.SessionStatsView.Empty;
Stat("Time:", IltParse.Duration(TimeSpan.FromSeconds(SessionClock(v))));
Stat("XP:", HudDraw.Compact(v.XpPerHour) + "/h");
Stat("Lum:", HudDraw.Compact(v.LumPerHour) + "/h");
Stat("Lum 5m:", HudDraw.Compact(v.LumLast5Min));
if (ImGui.IsItemHovered()) ImGui.SetTooltip("Luminance earned in the last five minutes.");
if (v.PassUpTracked)
{
Stat("Pass-up:", HudDraw.Compact(v.PassUpPerHour) + "/h");
if (ImGui.IsItemHovered()) ImGui.SetTooltip($"{v.LumPassUp:N0} this session.\n{IltSessionRates.PassUpTooltip}");
}
Stat("Kills:", HudDraw.Compact(v.KillsPerHour) + "/h");
if (!IltActive(hub)) return;
var r = hub!.Rates.Summary;
Stat("Coins:", HudDraw.Compact(r.CoinsPerHour) + "/h");
Stat("Pyr:", HudDraw.Compact(r.PyrealsPerHour) + "/h");
}
/// <summary>Seconds since the session started; 0 before it has (no login yet).</summary>
private static double SessionClock(RynthCore.Plugin.Shared.SessionStatsView v)
=> ReferenceEquals(v, RynthCore.Plugin.Shared.SessionStatsView.Empty)
? 0 : Math.Max(0, (DateTime.UtcNow - v.SessionStartUtc).TotalSeconds);
private static void RenderTarget(CombatHudSnapshot c)
{
if (c.TargetId == 0) { ImGui.TextDisabled("Target: none"); return; }
ImGui.TextColored(ColLabel, "Target:");
ImGui.SameLine();
ImGui.TextUnformatted(c.TargetName);
if (c.TargetDistance >= 0)
{
ImGui.SameLine();
ImGui.TextDisabled($"{c.TargetDistance:F0}yd");
}
HealthBar("##mrtargethp", c.TargetHealth);
}
/// <summary>The live summon when one is out, else the ILT Hub's next-essence line.</summary>
private static void RenderPet(IltHubController? hub, CombatHudSnapshot c)
{
if (c.PetId != 0)
{
RenderSummon(hub, c);
return;
}
if (!IltActive(hub)) { ImGui.TextDisabled("Summon: none"); return; }
string name = hub!.Pets.HudPetName;
string status = hub.Pets.HudPetStatus;
if (name.Length == 0) { ImGui.TextDisabled("No combat pet set"); return; }
ImGui.TextUnformatted(name);
var col = status switch { "Ready" => ColReady, "Out" => ColOut, "Healing" => ColBusy, _ => ColEmpty };
ImGui.TextColored(col, status);
}
private static void RenderSummon(IltHubController? hub, CombatHudSnapshot c)
{
ImGui.TextColored(ColLabel, "Summon:");
ImGui.SameLine();
ImGui.TextUnformatted(c.PetName);
if (IltActive(hub) && hub!.Pets.HudPetStatus == "Healing")
{
ImGui.SameLine();
ImGui.TextColored(ColBusy, "Healing");
}
HealthBar("##mrpethp", c.PetHealth);
long now = Environment.TickCount64;
if (c.PetExpiresAtMs != 0)
{
long leftMs = Math.Max(0, c.PetExpiresAtMs - now);
var left = TimeSpan.FromMilliseconds(leftMs);
string text = $"{FormatClock(left)} left";
if (c.PetLifespanSec > 0)
{
float frac = Math.Clamp(leftMs / (c.PetLifespanSec * 1000f), 0f, 1f);
var col = left.TotalSeconds <= 30 ? ColEmpty : left.TotalSeconds <= 90 ? ColBusy : ColOut;
Bar("##mrpettime", frac, text, col);
}
else
{
ImGui.TextColored(left.TotalSeconds <= 30 ? ColEmpty : ColOut, text);
}
}
else
{
// No RemainingLifespan from the server: show how long it has been out instead.
var up = TimeSpan.FromMilliseconds(Math.Max(0, now - c.PetSeenAtMs));
ImGui.TextDisabled($"Out {FormatClock(up)}");
if (ImGui.IsItemHovered()) ImGui.SetTooltip("The server hasn't reported this summon's lifespan yet.");
}
}
private static string FormatClock(TimeSpan t)
=> t.TotalHours >= 1 ? $"{(int)t.TotalHours}:{t.Minutes:00}:{t.Seconds:00}" : $"{t.Minutes}:{t.Seconds:00}";
/// <summary>Health ratio bar coloured green / yellow / red; "--" until the first health update.</summary>
private static void HealthBar(string id, float ratio)
{
if (ratio < 0f) { Bar(id, 0f, "HP --", ColLabel); return; }
var col = ratio > 0.6f ? ColReady : ratio > 0.3f ? ColBusy : ColEmpty;
Bar(id, ratio, $"HP {ratio * 100f:F0}%", col);
}
private static void Bar(string id, float fraction, string overlay, Vector4 color)
{
float w = Math.Max(ImGui.GetContentRegionAvail().X, 140f);
ImGui.PushStyleColor(ImGuiCol.PlotHistogram, color with { W = 0.85f });
ImGui.PushID(id);
ImGui.ProgressBar(fraction, new Vector2(w, 14f), overlay);
ImGui.PopID();
ImGui.PopStyleColor();
}
private void RenderStatButtons(IltHubController? hub)
{
float w = (ImGui.GetContentRegionAvail().X - ImGui.GetStyle().ItemSpacing.X) * 0.5f;
w = Math.Max(w, 70f);
if (ImGui.Button("Reset XP", new Vector2(w, 0)))
_hud.Post(() =>
{
_hud.SessionStats?.RequestReset();
_hud.Hub()?.Rates.Reset();
});
if (ImGui.IsItemHovered()) ImGui.SetTooltip("Start the session stats over (the Tracker panel keeps its own session).");
ImGui.SameLine();
if (ImGui.Button("Report", new Vector2(w, 0))) _hud.Post(ReportToChat);
if (ImGui.IsItemHovered()) ImGui.SetTooltip("Print the session rates in your chat window (local only).");
}
/// <summary>One-line session summary written to local chat (pump thread).</summary>
private void ReportToChat()
{
var v = _hud.SessionStats?.View ?? RynthCore.Plugin.Shared.SessionStatsView.Empty;
string time = IltParse.Duration(TimeSpan.FromSeconds(SessionClock(v)));
string line = $"[RynthAi] Session {time}: XP {HudDraw.Compact(v.XpPerHour)}/h, Lum {HudDraw.Compact(v.LumPerHour)}/h "
+ $"({HudDraw.Compact(v.LumLast5Min)} last 5m)";
if (v.PassUpTracked) line += $", Pass-up {HudDraw.Compact(v.PassUpPerHour)}/h";
line += $", Kills {HudDraw.Compact(v.KillsPerHour)}/h ({v.Kills:N0})";
var hub = _hud.Hub();
if (IltActive(hub))
{
var r = hub!.Rates.Summary;
line += $", Coins {HudDraw.Compact(r.CoinsPerHour)}/h, Pyr {HudDraw.Compact(r.PyrealsPerHour)}/h";
}
_hud.Chat(line);
}
private void RenderSlots(HudState s)
{
var slots = s.MiniRemoteSlots.ToArray();
var pack = _hud.Pack;
float slotSize = SlotSize(s);
ImGui.PushStyleVar(ImGuiStyleVar.FramePadding, new Vector2(1, 1));
ImGui.BeginGroup();
for (int i = 0; i < slots.Length; i++)
{
if (i % HudState.MiniRemoteColumns != 0) ImGui.SameLine();
var e = slots[i];
long count = e.IsEmpty ? 0 : pack.CountOf(e.Name);
ImGui.PushID(i);
bool clicked;
IntPtr tex = e.IsEmpty ? IntPtr.Zero : _hud.Icons.GetTexture(e.IconDid);
if (tex != IntPtr.Zero)
{
var tint = count == 0 ? new Vector4(1, 1, 1, 0.35f) : Vector4.One;
clicked = ImGui.ImageButton("##slot", tex, new Vector2(slotSize, slotSize), Vector2.Zero, Vector2.One, Vector4.Zero, tint);
}
else
{
string label = e.IsEmpty ? string.Empty : e.Name.Substring(0, 1).ToUpperInvariant();
if (e.IsEmpty) ImGui.PushStyleColor(ImGuiCol.Button, new Vector4(0.10f, 0.13f, 0.18f, 0.6f));
clicked = ImGui.Button(label + "##slot", new Vector2(slotSize + 2, slotSize + 2));
if (e.IsEmpty) ImGui.PopStyleColor();
}
if (ImGui.IsItemHovered())
ImGui.SetTooltip(e.IsEmpty ? EmptySlotTip(i) : $"{e.Name}\n{count:N0} carried\nClick to use, right-click for options.\nCtrl+wheel: box size.");
int slotIndex = i;
if (clicked)
{
// Empty slot: click assigns the selected (or last selected) pack item.
if (e.IsEmpty) _hud.Post(() => _hud.SetSlotFromSelection(slotIndex));
else
{
var entry = e;
_hud.Post(() => _hud.UseItem(entry));
}
}
AcceptItemDrop(slotIndex, e.IsEmpty);
if (ImGui.IsItemClicked(ImGuiMouseButton.Right))
{
_slotMenuIndex = i;
ImGui.OpenPopup(SlotPopup);
}
RenderSlotMenu(i, e);
ImGui.PopID();
}
ImGui.EndGroup();
ImGui.PopStyleVar();
// Ctrl+wheel over the grid: bigger / smaller boxes (the window / drawer refits to them).
var io = ImGui.GetIO();
if (io.KeyCtrl && io.MouseWheel != 0f && ImGui.IsItemHovered(ImGuiHoveredFlags.AllowWhenBlockedByActiveItem))
ResizeSlots(s, io.MouseWheel > 0f ? SlotSizeStep : -SlotSizeStep);
}
/// <summary>
/// ImGui drag-and-drop payload type for one inventory item (uint object id). Must match
/// InventoryFace.ItemPayloadType in RynthCore.Engine, which publishes it while dragging.
/// </summary>
private const string ItemPayloadType = "RYNTH_INV_ITEM";
/// <summary>
/// Payload type for an AC-inventory drag whose item the engine guessed from the game selection
/// (uint object id); engines that hook AC's drag start send the real item as ItemPayloadType
/// instead. Must match ItemDragBridge.NativePayloadType in RynthCore.Engine. A guess can be the
/// wrong item, so it is taken by empty slots only and never replaces an assigned one.
/// </summary>
private const string GameItemPayloadType = "RYNTH_GAME_ITEM";
/// <summary>
/// Makes the last slot button a drop target: RynthCore Inventory drags on any slot, game
/// inventory drags on <paramref name="empty"/> slots.
/// </summary>
private unsafe void AcceptItemDrop(int slot, bool empty)
{
if (!ImGui.BeginDragDropTarget()) return;
ImGuiPayloadPtr payload = ImGui.AcceptDragDropPayload(ItemPayloadType);
if (payload.NativePtr == null && empty) payload = ImGui.AcceptDragDropPayload(GameItemPayloadType);
if (payload.NativePtr != null && payload.Data != IntPtr.Zero && payload.DataSize >= sizeof(uint))
{
uint objectId = *(uint*)payload.Data;
_hud.Post(() => _hud.SetSlotFromItemId(slot, objectId));
}
ImGui.EndDragDropTarget();
}
private string EmptySlotTip(int index)
{
string candidate = _hud.AssignCandidate;
return candidate.Length > 0
? $"Slot {index + 1:00}: empty\nClick to assign {candidate}.\nOr drag an item here from the game inventory or the RynthCore Inventory.\nCtrl+wheel: box size."
: $"Slot {index + 1:00}: empty\nClick an item in your pack, then click here to assign it.\nOr drag an item here from the game inventory or the RynthCore Inventory.\nCtrl+wheel: box size.";
}
/// <summary>Per-slot right-click menu (opened inside the slot's ID scope).</summary>
private void RenderSlotMenu(int index, HudItemEntry e)
{
if (!ImGui.BeginPopup(SlotPopup)) return;
_slotMenuIndex = index;
ImGui.TextDisabled(e.IsEmpty ? $"Slot {index + 1:00}" : $"Slot {index + 1:00}: {e.Name}");
string candidate = _hud.AssignCandidate;
if (ImGui.MenuItem(candidate.Length > 0 ? $"Assign {candidate}" : "Assign selected item"))
_hud.Post(() => _hud.SetSlotFromSelection(index));
if (!e.IsEmpty && ImGui.MenuItem("Clear slot")) _hud.Post(() => _hud.ClearSlot(index));
ImGui.EndPopup();
}
private void RenderToggles(LegacyUiSettings settings)
{
var dash = _hud.Dashboard;
if (!ImGui.BeginTable("##mrtoggles", 3, ImGuiTableFlags.SizingStretchSame)) return;
Toggle("Macro", settings.IsMacroRunning, _ => dash.TogglePanelMacro());
Toggle("Combat", settings.EnableCombat, on => dash.SetSubsystemEnabled(0, on));
Toggle("Buff", settings.EnableBuffing, on => dash.SetSubsystemEnabled(1, on));
Toggle("Nav", settings.EnableNavigation, on => dash.SetSubsystemEnabled(2, on));
Toggle("Loot", settings.EnableLooting, on => dash.SetSubsystemEnabled(3, on));
Toggle("Meta", settings.EnableMeta, on => dash.SetSubsystemEnabled(4, on));
Toggle("Pet", settings.SummonPets, on => { settings.SummonPets = on; dash.SaveSettings(); });
ImGui.EndTable();
}
/// <summary>A checkbox in the next table cell whose change is applied on the pump thread.</summary>
private void Toggle(string label, bool current, Action<bool> apply)
{
ImGui.TableNextColumn();
bool v = current;
if (ImGui.Checkbox(label + "##mrt", ref v)) _hud.Post(() => apply(v));
}
private static void RenderBank(IltHubController? hub)
{
if (!IltActive(hub) || hub!.Options.IsOff(IltFeature.Bank)) return;
var b = hub.State.Bank;
if (b.LastUpdated == DateTime.MinValue) { ImGui.TextDisabled("Bank: not loaded (Options > Banking)"); return; }
Stat("P:", HudDraw.Compact(b.Pyreals));
Stat("Lum:", HudDraw.Compact(b.Luminance));
if (!ImGui.BeginTable("##mrbank", 2, ImGuiTableFlags.SizingStretchSame)) return;
ImGui.TableNextColumn(); Stat("LK:", HudDraw.Compact(b.LegendaryKeys));
ImGui.TableNextColumn(); Stat("MK:", HudDraw.Compact(b.MythicalKeys));
ImGui.TableNextColumn(); Stat("EC:", HudDraw.Compact(b.EnlightenedCoins));
ImGui.TableNextColumn(); Stat("WE:", HudDraw.Compact(b.WeaklyEnlightenedCoins));
// Prestige Coins (ACECustom 2026-10-04): only once the server has reported some.
if (b.PrestigeCoins > 0) { ImGui.TableNextColumn(); Stat("PC:", HudDraw.Compact(b.PrestigeCoins)); }
ImGui.EndTable();
}
private void RenderRebuff()
{
var dash = _hud.Dashboard;
ImGui.TextColored(ColLabel, "Rebuff:");
float w = (ImGui.GetContentRegionAvail().X - ImGui.GetStyle().ItemSpacing.X) * 0.5f;
w = Math.Max(w, 70f);
if (ImGui.Button("FB", new Vector2(w, 0))) _hud.Post(dash.RequestForceRebuff);
if (ImGui.IsItemHovered()) ImGui.SetTooltip("Force rebuff: recast every buff now.");
ImGui.SameLine();
if (ImGui.Button("CFB", new Vector2(w, 0))) _hud.Post(dash.RequestCancelForceRebuff);
if (ImGui.IsItemHovered()) ImGui.SetTooltip("Cancel the running rebuff.");
}
/// <summary>
/// The Options popup. <paramref name="embedded"/>: drawn in an engine surface, where the
/// floating window's lock and hide don't apply. The dashboard drawer offers the floating
/// window as a separate choice; the engine's Mini Remote window replaces it, so it doesn't.
/// </summary>
private void RenderOptions(HudState s, bool embedded)
{
if (_openOptions)
{
_openOptions = false;
ImGui.OpenPopup(OptionsPopup);
}
if (!ImGui.BeginPopup(OptionsPopup)) return;
ImGui.TextDisabled("Mini Remote sections");
Flag("Session stats", ref s.MiniShowStats);
Flag("Attack target", ref s.MiniShowTarget);
Flag("Pet / summon", ref s.MiniShowPet);
Flag("Item slots", ref s.MiniShowGems);
// The drawer's dashboard has these switches already; the setting is for the windows.
if (!InDrawer) Flag("Toggles", ref s.MiniShowToggles);
Flag("Bank", ref s.MiniShowBank);
Flag("Rebuff", ref s.MiniShowRebuff);
Flag("Translate", ref s.MiniShowTranslate);
Flag("Guardian answer", ref s.MiniShowGuardian);
ImGui.Separator();
Flag("Horizontal layout", ref s.MiniRemoteHorizontal);
RenderSlotSizeSlider(s);
if (embedded && _inWindow)
{
if (ImGui.MenuItem("Inventory HUDs setup...")) s.ShowSetup = true;
}
else if (embedded)
{
Flag("Floating window too", ref s.ShowMiniRemote);
if (ImGui.IsItemHovered()) ImGui.SetTooltip("Also show the Mini Remote as its own window (/ra remote).");
if (ImGui.MenuItem("Inventory HUDs setup...")) s.ShowSetup = true;
}
else
{
Flag("Lock position", ref s.MiniRemoteLocked);
if (ImGui.MenuItem("Inventory HUDs setup...")) s.ShowSetup = true;
if (ImGui.MenuItem("Hide Mini Remote")) s.ShowMiniRemote = false;
}
ImGui.EndPopup();
}
/// <summary>"Slot size" slider plus a reset, the menu twin of Ctrl+wheel over the slots.</summary>
private static void RenderSlotSizeSlider(HudState s)
{
float size = SlotSize(s);
ImGui.SetNextItemWidth(120f);
if (ImGui.SliderFloat("Slot size##mrslotsize", ref size, HudState.MinMiniRemoteSlotSize, HudState.MaxMiniRemoteSlotSize, "%.0f px"))
s.MiniRemoteSlotSize = MathF.Round(size);
if (ImGui.IsItemHovered()) ImGui.SetTooltip("Item slot box size (or Ctrl+wheel over the slots).");
ImGui.SameLine();
bool isDefault = s.MiniRemoteSlotSize == HudState.DefaultMiniRemoteSlotSize;
if (isDefault) ImGui.BeginDisabled();
if (ImGui.SmallButton("Default##mrslotsize")) s.MiniRemoteSlotSize = HudState.DefaultMiniRemoteSlotSize;
if (isDefault) ImGui.EndDisabled();
}
// ── Right-click menu: Character, then this server's plugin windows ─────────
/// <summary>RynthCore's server id for Infinite Leaftide (UI/ServerMenus.cs), the one RynthAi has features for.</summary>
private const string IltServerId = "ilt";
/// <summary>
/// The right-click menu. Top, "Character": windows every server has. Bottom: the server
/// section, i.e. the installed server plugins' windows for the world you're on (RynthCore
/// sends them, see <see cref="ServerMenuModel"/>), or the "Treat this world as ..." choices
/// when none matches.
/// </summary>
private void RenderMenu(HudState s)
{
if (!ImGui.BeginPopup(MenuPopup)) return;
try
{
RenderCharacterMenu(s);
RenderServerMenu(_hud.Hub());
}
finally { ImGui.EndPopup(); }
}
/// <summary>
/// "Character": RynthAi's own windows, the universal Mini Remote tabs (Quests, Pets), and
/// RynthCore's panels when it runs /rc commands.
/// </summary>
private void RenderCharacterMenu(HudState s)
{
ImGui.TextDisabled("Character");
var settings = _hud.Dashboard.Settings;
if (ImGui.MenuItem("Spells##mrspells", "/ra spells", settings.ShowSpellsWindow))
settings.ShowSpellsWindow = !settings.ShowSpellsWindow;
if (ImGui.IsItemHovered()) ImGui.SetTooltip("The spell catalog and buff profiles.");
foreach (IltSection section in IltSections.Tabs)
{
if (!IltSections.IsUniversal(section)) continue;
string id = IltSections.TabId(section);
if (ImGui.MenuItem(IltSections.Label(section) + "##mrchar_" + id, "/ra hub open " + id))
_hud.HandleTabCommand(id, "show");
}
if (_hud.Host.HasInvokeChatParser)
{
if (ImGui.MenuItem("Skills##mrskills", "/rc skills")) _hud.RunEngineCommand("/rc skills toggle");
if (ImGui.MenuItem("Inventory##mrinv", "/rc inventory")) _hud.RunEngineCommand("/rc inventory");
if (ImGui.MenuItem("Item Count##mritemcount", "/rc itemcount")) _hud.RunEngineCommand("/rc itemcount");
}
if (ImGui.MenuItem("Inventory HUDs setup...##mrsetup")) s.ShowSetup = true;
}
/// <summary>
/// The server section. Each section RynthCore marks active is listed, and so is Infinite
/// Leaftide while this character's "Treat this world as ILT" is on (RynthAi's own override).
/// Without RynthCore's list it falls back to RynthAi's ILT entries.
/// </summary>
private void RenderServerMenu(IltHubController? hub)
{
ServerMenuGroup[]? groups = ServerMenuModel.Groups;
if (groups == null)
{
RenderLocalIltMenu(hub);
return;
}
if (groups.Length == 0) return; // no server plugin installed
bool any = false;
foreach (ServerMenuGroup g in groups)
{
bool ilt = g.Id.Equals(IltServerId, StringComparison.OrdinalIgnoreCase);
bool forcedHere = ilt && hub?.ForceIltWorld == true;
if (!g.Active && !forcedHere) continue;
any = true;
ImGui.Separator();
ImGui.TextDisabled("Server: " + (g.Active ? g.Name : g.Name + " (forced)"));
foreach (ServerMenuEntry item in g.Items)
{
string? tab = ServerMenuModel.TabOf(item.Feature);
// Universal tabs are under Character; RynthCore 2026.10.5.30 and older list them here too.
if (tab != null && IltSections.TryParse(tab, out IltSection listed) && IltSections.IsUniversal(listed)) continue;
bool enabled = tab == null || TabAvailable(hub, tab);
if (ImGui.MenuItem(item.Label + "##mrsrv_" + g.Id, item.Command, false, enabled))
RunServerItem(item, tab);
if (item.Tooltip.Length > 0 && ImGui.IsItemHovered(ImGuiHoveredFlags.AllowWhenDisabled))
ImGui.SetTooltip(enabled ? item.Tooltip : item.Tooltip + "\nShows once the server reports this feature on.");
}
if (ilt) RenderIltStatus(hub);
}
if (any) return;
ImGui.Separator();
ImGui.TextDisabled("Server: no installed server plugin matches this world");
foreach (ServerMenuGroup g in groups)
{
if (g.ForceCommand.Length == 0) continue;
if (ImGui.MenuItem("Treat this world as " + g.Name + "##mrforce_" + g.Id, g.ForceCommand))
ForceServer(g, hub);
if (ImGui.IsItemHovered())
ImGui.SetTooltip("Shows this server's windows here anyway. It only says which world this is:\nthe server still decides which features exist.");
}
}
/// <summary>A Mini Remote tab switches here and now; anything else is a RynthCore command.</summary>
private void RunServerItem(ServerMenuEntry item, string? tab)
{
if (tab != null) _hud.HandleTabCommand(tab, "show");
else if (item.Command.Length > 0) _hud.RunEngineCommand(item.Command);
}
/// <summary>
/// Forces a server: RynthCore's session override, plus for Infinite Leaftide this character's
/// "Treat this world as ILT" (so RynthAi's tabs come too).
/// </summary>
private void ForceServer(ServerMenuGroup g, IltHubController? hub)
{
if (g.Id.Equals(IltServerId, StringComparison.OrdinalIgnoreCase) && hub != null) hub.ForceIltWorld = true;
_hud.RunEngineCommand(g.ForceCommand);
}
private static bool TabAvailable(IltHubController? hub, string tab) =>
hub != null && IltSections.TryParse(tab, out IltSection section) && IltSections.IsTab(section) && hub.SectionAvailable(section);
/// <summary>
/// RynthAi's own Infinite Leaftide entries, for when RynthCore sends no server list (older
/// RynthCore, or its ImGui layer off): the tabs, and the Guardian / Bounties panels.
/// </summary>
private void RenderLocalIltMenu(IltHubController? hub)
{
if (hub == null || !hub.OffersTabs) return;
ImGui.Separator();
ImGui.TextDisabled("Server: Infinite Leaftide");
foreach (IltSection section in IltSections.Tabs)
{
if (IltSections.IsUniversal(section)) continue; // under Character
if (ImGui.MenuItem(IltSections.Label(section) + "##mrlocal", string.Empty, false, hub.SectionAvailable(section)))
_hud.HandleTabCommand(IltSections.TabId(section), "show");
}
if (ImGui.MenuItem("Guardian##mrlocal", "/rc guardian", false, hub.SectionAvailable(IltSection.Guardian)))
_hud.Post(() => hub.OpenEnginePanel("guardian", "Guardian", "show"));
if (ImGui.MenuItem("Bounties##mrlocal", "/rc bounties"))
_hud.Post(() => hub.OpenEnginePanel("bounties", "Bounties", "show"));
RenderIltStatus(hub);
}
/// <summary>
/// Under the Infinite Leaftide section while no ILT feature is on: why, this character's
/// "Treat this world as ILT" override and a server-features refresh.
/// </summary>
private static void RenderIltStatus(IltHubController? hub)
{
if (hub == null || hub.Available) return;
var o = hub.Options;
ImGui.TextDisabled(!o.IsIltLikeWorld ? "Not an ILT world."
: o.IsRefreshing || o.LastRefreshUtc == DateTime.MinValue ? "Checking server features..."
: "No ILT features reported.");
bool force = hub.ForceIltWorld;
if (ImGui.Checkbox("Treat this world as ILT##mrforce", ref force)) hub.ForceIltWorld = force;
if (ImGui.IsItemHovered())
ImGui.SetTooltip("World-identity override only: RynthAi asks the server which features exist.\nIt never turns a feature on by itself.");
if (ImGui.MenuItem("Refresh server features##mrrefresh")) hub.RequestOptionsRefresh();
}
private static void Flag(string label, ref bool value)
{
bool v = value;
if (ImGui.Checkbox(label, ref v)) value = v;
}
}

View file

@ -0,0 +1,84 @@
// ServerMenuModel.cs - The server sections RynthCore pushes for the Mini Remote's right-click menu.
//
// RynthCore defines each server it knows (Infinite Leaftide today), whether the client is on it
// (or forced onto it), and the windows its installed plugins add for it (UI/ServerMenus.cs in
// RynthCore). It sends that list as the "servermenu" remote command when it changes, and again
// every 30 s. The payload is one tab-separated line per section ("S", id, name, active 0/1, force
// command), then its items ("I", label, command, tooltip, feature).
//
// Groups stays null until the first push: an older RynthCore, or the ImGui shell off. The menu
// then falls back to RynthAi's own ILT entries.
using System;
using System.Collections.Generic;
using System.Threading;
namespace RynthCore.Plugin.RynthAi.Huds;
/// <summary>A server section item: an engine "/rc" command, or a Mini Remote tab ("tab:&lt;id&gt;" feature).</summary>
internal sealed record ServerMenuEntry(string Label, string Command, string Tooltip, string Feature);
/// <summary>One server's section: shown while <see cref="Active"/> (detected or forced in RynthCore).</summary>
internal sealed record ServerMenuGroup(string Id, string Name, bool Active, string ForceCommand, ServerMenuEntry[] Items);
internal static class ServerMenuModel
{
/// <summary>Feature prefix for items that are Mini Remote tabs (drawn by RynthAi itself).</summary>
public const string TabFeaturePrefix = "tab:";
private static ServerMenuGroup[]? _groups;
/// <summary>The latest sections from RynthCore; null until it sends any. Any thread.</summary>
public static ServerMenuGroup[]? Groups => Volatile.Read(ref _groups);
/// <summary>Pump thread: stores a "servermenu" push. A malformed line is skipped, never thrown.</summary>
public static void Apply(string payload) => Volatile.Write(ref _groups, Parse(payload));
/// <summary>
/// Parses a payload. Items before the first section line, short lines and unknown line kinds
/// are skipped.
/// </summary>
public static ServerMenuGroup[] Parse(string? payload)
{
var groups = new List<ServerMenuGroup>();
if (string.IsNullOrEmpty(payload)) return groups.ToArray();
string id = "", name = "", force = "";
bool active = false, open = false;
var items = new List<ServerMenuEntry>();
void Close()
{
if (open) groups.Add(new ServerMenuGroup(id, name, active, force, items.ToArray()));
items.Clear();
open = false;
}
foreach (string raw in payload.Split('\n'))
{
string line = raw.TrimEnd('\r');
if (line.Length == 0) continue;
string[] f = line.Split('\t');
if (f[0] == "S" && f.Length >= 5)
{
Close();
id = f[1];
name = f[2];
active = f[3] == "1";
force = f[4];
open = id.Length > 0 && name.Length > 0;
}
else if (f[0] == "I" && f.Length >= 5 && open && f[1].Length > 0)
{
items.Add(new ServerMenuEntry(f[1], f[2], f[3], f[4]));
}
}
Close();
return groups.ToArray();
}
/// <summary>The tab id of a "tab:&lt;id&gt;" feature, else null.</summary>
public static string? TabOf(string feature) =>
feature.StartsWith(TabFeaturePrefix, StringComparison.OrdinalIgnoreCase) && feature.Length > TabFeaturePrefix.Length
? feature.Substring(TabFeaturePrefix.Length)
: null;
}

View file

@ -0,0 +1,637 @@
// IltAttributeRaiser.cs — Infinite attributes: spend unassigned XP with the server's /attr.
//
// ACECustom (Infinite Leaftide) lets attributes and vitals go past the retail cap, so the
// client's XP tables stop applying. The server is the only source of truth:
// "/xp all" → "[XP] Your XP cost for next 1 Strength level is: 1,234" per stat
// "/attr <abbr> <n>" → "[ATTR] Strength attribute raised by 1, costing 1,234!"
// (Same commands UB's Leaftide XP Calculator drives; it raises one level at a time and
// re-reads the costs after each confirmation, which is what this does too.)
//
// Raise now / auto-raise run one loop: read costs → pick a stat → /attr <abbr> 1 → wait for
// the [ATTR] reply → read costs again → ... until nothing ticked is affordable, a reply is
// not a success, or MaxRaisesPerRun. Only the ticked stats are ever spent on, never below
// the reserve (AttrKeepXp). Which stat comes next depends on the raise mode:
// Priority the first ticked stat in the order that is affordable (fills the top stat)
// RoundRobin one level per ticked stat in order, then around again
// Cheapest the ticked stat with the lowest next-level cost
// Manual +1 / +10 buttons send "/attr <abbr> N" straight to the server (its reply shows in chat)
// once the known (+1) or projected (+10, 7.7% per level as in UB) cost fits the unassigned XP.
//
// Gated on ServerFeatureGate (via IltServerOptions.IsIltLikeWorld) and on the server not
// reporting /xp off. Everything here runs on the plugin pump thread.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace RynthCore.Plugin.RynthAi.IltHub;
internal sealed class IltAttributeRaiser
{
/// <summary>Raise modes (IltCharacterState.AttrRaiseMode).</summary>
public enum Mode { Priority = 0, RoundRobin = 1, Cheapest = 2 }
/// <summary>/attr abbreviation, display name, vital?</summary>
public sealed record Stat(string Abbr, string Name, bool Vital);
public static readonly Stat[] Stats =
{
new("str", "Strength", false), new("end", "Endurance", false), new("coo", "Coordination", false),
new("qui", "Quickness", false), new("foc", "Focus", false), new("sel", "Self", false),
new("hea", "Health", true), new("sta", "Stamina", true), new("man", "Mana", true),
};
/// <summary>UB's default priority (Coordination, Quickness, Strength, Endurance, Focus, Self, vitals).</summary>
public static readonly string[] DefaultOrder = { "coo", "qui", "str", "end", "foc", "sel", "hea", "sta", "man" };
public const int MaxRaisesPerRun = 200;
/// <summary>
/// Per-level growth for projecting several levels from the one cost "/xp all" reports (UB's
/// Leaftide XP tab uses the same 7.7%). The server prices each level itself; this only labels
/// the +10 button and gates it on the XP you have.
/// </summary>
public const double ProjectedLevelGrowth = 0.077;
private const long FirstAutoDelayMs = 30_000; // after login / arming, before the first auto run
private const int ReplyTimeoutMs = 8000;
/// <summary>A run with no reply/step for this long is ended (a lost callback must not wedge it).</summary>
private const long StallMs = 45_000;
/// <summary>"Your base Strength is now 250!" / "Your base Maximum Health is now 900!" (older servers / UB wording).</summary>
private static readonly Regex BaseNow = new(@"Your base (?:Maximum )?(\w+) is now (\d+)!", RegexOptions.Compiled | RegexOptions.CultureInvariant);
private readonly IltHubContext _ctx;
// Last known costs (display, and the passive chat reader). A run decides only from _runCosts:
// the costs in the "/xp all" reply read right before that step, never an older value.
private readonly Dictionary<string, long> _cost = new(StringComparer.OrdinalIgnoreCase);
private Dictionary<string, long> _runCosts = new(StringComparer.OrdinalIgnoreCase);
private readonly Dictionary<string, int> _base = new(StringComparer.OrdinalIgnoreCase);
private long _costsAtMs;
private DateTime _costsAtLocal;
// Opening the Progression tab reads the costs once per login, like UB's XP tab does on load.
private bool _autoCostsTried;
// Run state. _runId guards against a capture that completes after Stop / a newer run.
private enum Phase { Idle, ReadingCosts, Raising }
private Phase _phase;
private int _runId;
private bool _runAuto;
private int _runRaised;
private long _runSpent;
private readonly Dictionary<string, int> _runGains = new(StringComparer.OrdinalIgnoreCase);
private int _rrNext;
private string _raisingAbbr = string.Empty;
private long _raisingCost;
private long _lastProgressMs;
private long _nextAutoAtMs;
private volatile string _status = "Idle.";
private volatile string _lastRun = string.Empty;
public IltAttributeRaiser(IltHubContext ctx) => _ctx = ctx;
/// <summary>
/// True while another XP spender runs (IltProgression's spend-before-/enl loop sends /attr
/// outside the capture queue). Nothing here starts, by hand or on the timer, while it is.
/// </summary>
public Func<bool>? HoldOff { get; set; }
private bool HeldOff
{
get { try { return HoldOff?.Invoke() == true; } catch { return false; } }
}
private IltCharacterState C => _ctx.State.Character;
public bool Running => _phase != Phase.Idle;
// ── Order / selection helpers (also used by IltHubStore.Normalize) ─────────
public static Stat? Find(string keyOrName)
{
if (string.IsNullOrWhiteSpace(keyOrName)) return null;
string k = keyOrName.Trim();
foreach (var s in Stats)
if (s.Abbr.Equals(k, StringComparison.OrdinalIgnoreCase) || s.Name.Equals(k, StringComparison.OrdinalIgnoreCase))
return s;
// Cost lines may say "MaxHealth" / "Maximum Health"; the reply may abbreviate.
string lower = k.ToLowerInvariant().Replace(" ", "");
if (lower.StartsWith("maximum")) lower = lower.Substring(7);
else if (lower.StartsWith("max")) lower = lower.Substring(3);
foreach (var s in Stats)
if (s.Name.Equals(lower, StringComparison.OrdinalIgnoreCase) || lower.StartsWith(s.Abbr, StringComparison.Ordinal))
return s;
return null;
}
/// <summary>All nine abbreviations exactly once: saved order first, missing ones appended, junk dropped.</summary>
public static List<string> RepairOrder(List<string>? order)
{
var result = new List<string>();
foreach (string k in order ?? new List<string>())
{
Stat? s = Find(k);
if (s != null && !result.Contains(s.Abbr)) result.Add(s.Abbr);
}
foreach (string k in DefaultOrder)
if (!result.Contains(k)) result.Add(k);
return result;
}
public static List<string> RepairSelection(List<string>? selection)
{
var result = new List<string>();
foreach (string k in selection ?? new List<string>())
{
Stat? s = Find(k);
if (s != null && !result.Contains(s.Abbr)) result.Add(s.Abbr);
}
return result;
}
/// <summary>
/// Picks the next stat to raise. Pure (unit-testable): <paramref name="order"/> is the
/// priority order, <paramref name="ticked"/> the stats allowed, <paramref name="cost"/> the
/// known next-level costs, <paramref name="budget"/> what may be spent. Round robin starts at
/// <paramref name="rrNext"/> and returns the index after the pick there.
/// </summary>
public static string? Pick(Mode mode, IReadOnlyList<string> order, ICollection<string> ticked,
IReadOnlyDictionary<string, long> cost, long budget, ref int rrNext)
{
if (budget <= 0 || order.Count == 0) return null;
bool Affordable(string k) => ticked.Contains(k) && cost.TryGetValue(k, out long c) && c > 0 && c <= budget;
switch (mode)
{
case Mode.RoundRobin:
for (int step = 0; step < order.Count; step++)
{
int i = ((rrNext % order.Count) + step) % order.Count;
if (!Affordable(order[i])) continue;
rrNext = i + 1;
return order[i];
}
return null;
case Mode.Cheapest:
string? best = null;
long bestCost = long.MaxValue;
foreach (string k in order) // ties go to the higher-priority stat
{
if (!Affordable(k)) continue;
long c = cost[k];
if (c < bestCost) { best = k; bestCost = c; }
}
return best;
default:
foreach (string k in order)
if (Affordable(k)) return k;
return null;
}
}
// ── Gate ──────────────────────────────────────────────────────────────────
/// <summary>Why the raiser can't run here, or null when it can.</summary>
public string? Blocker()
{
if (!_ctx.Options.IsIltLikeWorld)
return "Server features are off for this world (Settings > Misc > Server Features).";
if (_ctx.Options.IsOff(IltFeature.Xp)) return "This server reports /xp as unavailable.";
if (!_ctx.Host.HasInvokeChatParser) return "This engine build can't send chat commands.";
return null;
}
// ── Pump-thread lifecycle ─────────────────────────────────────────────────
/// <summary>Tick. <paramref name="holdOff"/>: another XP spender (auto-enlighten's loop) is running.</summary>
public void Tick(long nowMs, bool holdOff)
{
if (Running && nowMs - _lastProgressMs > StallMs) { Finish($"Stopped: no reply for {StallMs / 1000} s."); return; }
if (!C.AttrAutoRaise || Running || holdOff || HeldOff) return;
if (_nextAutoAtMs == 0) { _nextAutoAtMs = nowMs + FirstAutoDelayMs; return; }
if (nowMs < _nextAutoAtMs) return;
_nextAutoAtMs = nowMs + Math.Clamp(C.AttrAutoRaiseMinutes, 1, 1440) * 60_000L;
if (Blocker() != null || C.AttrRaiseStats.Count == 0) return;
if (_ctx.Inventory.PlayerQuad(IltInventory.QuadAvailableXp) <= Math.Max(0, C.AttrKeepXp)) return;
Start(auto: true);
}
/// <summary>Passive: keeps costs / base values current when the player runs the commands by hand.</summary>
public void OnChat(string text)
{
var cost = IltParse.XpCost.Match(text);
if (cost.Success)
{
Stat? s = Find(cost.Groups[1].Value);
if (s != null) { _cost[s.Abbr] = IltParse.ParseLeadingLong(cost.Groups[2].Value); MarkCostsRead(); }
return;
}
var now = BaseNow.Match(text);
if (now.Success)
{
Stat? s = Find(now.Groups[1].Value);
if (s != null && int.TryParse(now.Groups[2].Value, out int v)) _base[s.Abbr] = v;
}
}
public void OnLogout()
{
_runId++;
_phase = Phase.Idle;
_cost.Clear();
_runCosts.Clear();
_base.Clear();
_costsAtMs = 0;
_autoCostsTried = false;
_nextAutoAtMs = 0;
_status = "Idle.";
}
// ── Runs ──────────────────────────────────────────────────────────────────
/// <summary>Starts a spend run (manual "Raise now" or the auto timer).</summary>
public void Start(bool auto)
{
if (Running) return;
string? blocked = Blocker();
if (blocked != null) { _status = blocked; return; }
if (HeldOff) { _status = "Auto-enlighten is spending XP right now; try again when it finishes."; return; }
if (C.AttrRaiseStats.Count == 0) { _status = "Tick at least one attribute or vital to raise."; return; }
_runId++;
_runAuto = auto;
_runRaised = 0;
_runSpent = 0;
_runGains.Clear();
_rrNext = 0;
_runCosts = new Dictionary<string, long>(StringComparer.OrdinalIgnoreCase);
_lastProgressMs = IltHubContext.NowMs;
RynthLog.Trace(LogCat.IltProgression, $"attr raise run {_runId} start (auto={auto}, mode={(Mode)C.AttrRaiseMode}, keep={C.AttrKeepXp}, stats={string.Join(",", C.AttrRaiseStats)})");
ReadCosts(_runId, thenStep: true);
}
public void Stop(string why = "Stopped.")
{
if (!Running) return;
Finish(why);
}
/// <summary>Re-reads the costs only (the panel's Refresh button).</summary>
public void RefreshCosts()
{
if (Running || Blocker() != null) return;
ReadCosts(_runId, thenStep: false);
}
/// <summary>Reads the costs once per login when the Progression tab is first shown. Pump thread.</summary>
public void EnsureCosts()
{
if (_autoCostsTried || _costsAtMs != 0 || Running || Blocker() != null) return;
_autoCostsTried = true;
ReadCosts(_runId, thenStep: false);
}
/// <summary>
/// XP for <paramref name="levels"/> raises when the next one costs <paramref name="nextCost"/>,
/// each level <see cref="ProjectedLevelGrowth"/> dearer than the last. Saturates at long.MaxValue.
/// </summary>
public static long ProjectCost(long nextCost, int levels)
{
if (nextCost <= 0 || levels <= 0) return 0;
double total = 0, step = nextCost;
for (int i = 0; i < levels; i++)
{
total += step;
step *= 1 + ProjectedLevelGrowth;
}
return total >= long.MaxValue ? long.MaxValue : (long)total;
}
private void MarkCostsRead()
{
_costsAtMs = IltHubContext.NowMs;
_costsAtLocal = DateTime.Now;
}
/// <summary>
/// "+N" button: sends "/attr abbr N"; the server's reply shows in chat. Refused up front when
/// the known (or, for N &gt; 1, projected) cost is more than the unassigned XP, like UB's XP tab.
/// </summary>
public void RaiseManual(string key, int levels)
{
Stat? s = Find(key);
if (s == null || levels <= 0) return;
if (Running) { _status = "Wait for the current raise run to finish (or Stop it)."; return; }
string? blocked = Blocker();
if (blocked != null) { _status = blocked; return; }
if (HeldOff) { _status = "Auto-enlighten is spending XP right now; try again when it finishes."; return; }
levels = Math.Min(levels, 1000);
if (_cost.TryGetValue(s.Abbr, out long next) && next > 0)
{
long need = ProjectCost(next, levels);
long have = _ctx.Inventory.PlayerQuad(IltInventory.QuadAvailableXp);
if (need > have)
{
_status = $"Not enough unassigned XP for {s.Name} +{levels}: need {(levels > 1 ? "~" : "")}{IltParse.Compact(need)}, have {IltParse.Compact(have)}.";
return;
}
}
RynthLog.Trace(LogCat.IltProgression, $"attr manual raise {s.Abbr} +{levels}");
int run = _runId;
_ctx.Capture.Enqueue(new IltChatRequest
{
Command = $"/attr {s.Abbr} {levels}",
IsResponseLine = IsAttrReply,
IsTerminator = IsAttrReply,
IdleEndMs = 600,
FirstLineTimeoutMs = ReplyTimeoutMs,
Eat = false,
OnComplete = r =>
{
string reply = r.TerminatorLine ?? r.Lines.FirstOrDefault() ?? (r.TimedOut ? "no reply" : "");
_status = $"{s.Name} +{levels}: {reply}";
if (run == _runId && !Running) ReadCosts(_runId, thenStep: false);
},
});
_status = $"Sent /attr {s.Abbr} {levels}...";
}
private static bool IsAttrReply(string t)
=> t.StartsWith("[ATTR]", StringComparison.OrdinalIgnoreCase) || t.StartsWith("Your base", StringComparison.OrdinalIgnoreCase);
private void ReadCosts(int run, bool thenStep)
{
// A plain refresh doesn't stack on one already queued; a run always gets its own reply.
if (!thenStep && _ctx.Capture.IsPending("/xp all")) return;
if (thenStep)
{
_phase = Phase.ReadingCosts;
if (_runRaised == 0) _status = "Reading XP costs (/xp all)...";
}
_ctx.Capture.Enqueue(new IltChatRequest
{
Command = "/xp all",
IsResponseLine = t => t.StartsWith("[XP]", StringComparison.OrdinalIgnoreCase),
IdleEndMs = 900,
FirstLineTimeoutMs = ReplyTimeoutMs,
Eat = true,
OnComplete = r => Guard(run, () =>
{
if (r.UnknownCommand) { _ctx.Options.Set(IltFeature.Xp, IltTri.Off); if (run == _runId && thenStep) Finish("This server has no /xp command."); return; }
var fresh = new Dictionary<string, long>(StringComparer.OrdinalIgnoreCase);
foreach (string line in r.Lines)
{
var m = IltParse.XpCost.Match(line);
if (!m.Success) continue;
Stat? s = Find(m.Groups[1].Value);
if (s == null) continue;
fresh[s.Abbr] = IltParse.ParseLeadingLong(m.Groups[2].Value);
}
foreach (var kv in fresh) _cost[kv.Key] = kv.Value;
if (fresh.Count > 0) MarkCostsRead();
RynthLog.Trace(LogCat.IltProgression, $"attr costs: {fresh.Count} line(s) (timedOut={r.TimedOut})");
if (!thenStep || run != _runId || !Running) return;
if (fresh.Count == 0) { Finish(r.TimedOut ? "No reply to /xp all." : "No cost lines in the /xp all reply."); return; }
_runCosts = fresh; // a stat missing from this reply is not raised this step
_lastProgressMs = IltHubContext.NowMs;
Step(run);
}),
});
}
private void Step(int run)
{
if (run != _runId || !Running) return;
// The world can leave Server Features (or /xp go off) mid-run, and auto-enlighten can start.
if (Blocker() is string blocked) { Finish("Stopped: " + blocked); return; }
if (HeldOff) { Finish("Stopped: auto-enlighten started spending XP."); return; }
if (_runRaised >= MaxRaisesPerRun) { Finish($"Stopped after {MaxRaisesPerRun} raises (runs again later)."); return; }
long have = _ctx.Inventory.PlayerQuad(IltInventory.QuadAvailableXp);
long budget = have - Math.Max(0, C.AttrKeepXp);
var ticked = new HashSet<string>(C.AttrRaiseStats, StringComparer.OrdinalIgnoreCase);
string? pick = Pick((Mode)Math.Clamp(C.AttrRaiseMode, 0, 2), C.AttrOrder, ticked, _runCosts, budget, ref _rrNext);
if (pick == null)
{
Finish(_runRaised == 0
? (budget <= 0 ? "Nothing to spend (unassigned XP is at or below the reserve)."
: "Nothing affordable among the ticked stats.")
: string.Empty);
return;
}
Stat s = Find(pick)!;
_phase = Phase.Raising;
_raisingAbbr = s.Abbr;
_raisingCost = _runCosts.TryGetValue(s.Abbr, out long c) ? c : 0;
_status = $"Raising {s.Name} +1 (cost {IltParse.Compact(_raisingCost)})...";
_ctx.Capture.Enqueue(new IltChatRequest
{
Command = $"/attr {s.Abbr} 1",
IsResponseLine = IsAttrReply,
IsTerminator = IsAttrReply,
IdleEndMs = 600,
FirstLineTimeoutMs = ReplyTimeoutMs,
Eat = true,
OnComplete = r => Guard(run, () => OnRaiseReply(run, s, r)),
});
}
private void OnRaiseReply(int run, Stat s, IltChatResult r)
{
if (run != _runId || !Running) return;
string reply = r.TerminatorLine ?? r.Lines.FirstOrDefault() ?? string.Empty;
var ok = IltParse.AttrRaised.Match(reply);
var baseNow = BaseNow.Match(reply);
// The reply must be about the stat we raised (another /attr sender could answer first).
if (ok.Success && Find(ok.Groups[1].Value) != s) ok = Match.Empty;
if (baseNow.Success && Find(baseNow.Groups[1].Value) != s) baseNow = Match.Empty;
if (!ok.Success && !baseNow.Success)
{
RynthLog.Trace(LogCat.IltProgression, $"attr raise {s.Abbr}: not a success ('{reply}', timedOut={r.TimedOut}, unknown={r.UnknownCommand})");
Finish(r.UnknownCommand ? "This server has no /attr command."
: reply.Length > 0 ? $"Server: {reply}" : "No reply to /attr.");
return;
}
long spent = ok.Success ? IltParse.ParseLeadingLong(ok.Groups[3].Value) : _raisingCost;
int levels = ok.Success && int.TryParse(ok.Groups[2].Value, out int n) ? n : 1;
if (baseNow.Success && int.TryParse(baseNow.Groups[2].Value, out int v)) _base[s.Abbr] = v;
else if (_base.TryGetValue(s.Abbr, out int b)) _base[s.Abbr] = b + levels;
_runGains[s.Abbr] = (_runGains.TryGetValue(s.Abbr, out int g) ? g : 0) + levels;
_runRaised += levels;
_runSpent += spent;
_cost.Remove(s.Abbr); // its next level costs more; re-read before deciding again
_runCosts.Clear();
_lastProgressMs = IltHubContext.NowMs;
_status = $"Raised {s.Name} (+{_runRaised} this run, {IltParse.Compact(_runSpent)} XP)...";
ReadCosts(run, thenStep: true);
}
/// <summary>Runs a capture callback; an exception ends the run instead of leaving it Running.</summary>
private void Guard(int run, Action body)
{
try { body(); }
catch (Exception ex)
{
RynthLog.Exception(LogCat.IltProgression, ex, "attr raise callback");
if (run == _runId && Running) Finish("Stopped: internal error (see the RynthAi log).");
}
}
private void Finish(string reason)
{
_phase = Phase.Idle;
_runId++; // late callbacks from this run are ignored
string summary = _runRaised > 0
? "Raised " + string.Join(", ", C.AttrOrder.Where(_runGains.ContainsKey).Select(k => $"{Find(k)!.Name} +{_runGains[k]}"))
+ $" ({IltParse.Compact(_runSpent)} XP)."
: string.Empty;
string text = (summary + (reason.Length > 0 ? (summary.Length > 0 ? " " : "") + reason : "")).Trim();
if (text.Length == 0) text = "Done.";
_status = text;
_lastRun = $"{DateTime.Now:t} {(_runAuto ? "auto" : "manual")}: {text}";
RynthLog.Trace(LogCat.IltProgression, $"attr raise run finished: {text}");
if (_runRaised > 0) _ctx.Chat($"[Mini Remote] Attribute raise ({(_runAuto ? "auto" : "manual")}): {text}");
}
// ── Engine Skills panel bridge ────────────────────────────────────────────
/// <summary>Appends <c>"attr":{...}</c> for the Progression tab.</summary>
public void AppendJson(StringBuilder sb)
{
string? blocked = Blocker();
long have = _ctx.Inventory.PlayerQuad(IltInventory.QuadAvailableXp);
long budget = have - Math.Max(0, C.AttrKeepXp);
long now = IltHubContext.NowMs;
sb.Append("\"attr\":{\"off\":").Append(blocked != null ? "true" : "false");
Str(sb, "reason", blocked ?? string.Empty);
sb.Append(",\"auto\":").Append(C.AttrAutoRaise ? "true" : "false")
.Append(",\"every\":").Append(Math.Clamp(C.AttrAutoRaiseMinutes, 1, 1440))
.Append(",\"mode\":").Append(Math.Clamp(C.AttrRaiseMode, 0, 2))
.Append(",\"running\":").Append(Running ? "true" : "false");
Str(sb, "keep", C.AttrKeepXp > 0 ? IltParse.Compact(C.AttrKeepXp) : "0");
// The reserve box edits the exact number (the compact form above is lossy).
Str(sb, "keepFull", IltParse.N0(Math.Max(0, C.AttrKeepXp)));
Str(sb, "status", _status);
Str(sb, "lastRun", _lastRun);
Str(sb, "unassigned", $"Unassigned XP {IltParse.Compact(have)}"
+ (C.AttrKeepXp > 0 ? $" (spendable {IltParse.Compact(Math.Max(0, budget))})" : ""));
string next = !C.AttrAutoRaise ? string.Empty
: Running ? "running"
: _nextAutoAtMs <= 0 ? "soon"
: IltParse.Duration(TimeSpan.FromMilliseconds(Math.Max(0, _nextAutoAtMs - now)));
Str(sb, "next", next);
Str(sb, "costsAge", _costsAtMs == 0 ? "costs not read yet" : $"costs read {Ago(now - _costsAtMs)} ago");
Str(sb, "updated", _costsAtMs == 0 ? "-" : _costsAtLocal.ToString("HH:mm:ss"));
int level = _ctx.Inventory.PlayerInt(IltInventory.IntLevel);
long totalXp = _ctx.Inventory.PlayerQuad(IltInventory.QuadTotalXp);
Str(sb, "xpHeader", $"Level {(level > 0 ? level.ToString() : "?")} Total XP {(totalXp > 0 ? IltParse.Compact(totalXp) : "?")} Unassigned {IltParse.Compact(have)}");
var ticked = new HashSet<string>(C.AttrRaiseStats, StringComparer.OrdinalIgnoreCase);
sb.Append(",\"rows\":[");
bool first = true;
foreach (string k in C.AttrOrder)
{
Stat? s = Find(k);
if (s == null) continue;
if (!first) sb.Append(',');
first = false;
bool known = _cost.TryGetValue(s.Abbr, out long c) && c > 0;
sb.Append('{');
Str(sb, "key", s.Abbr, first: true);
Str(sb, "label", s.Name);
sb.Append(",\"vital\":").Append(s.Vital ? "true" : "false")
.Append(",\"on\":").Append(ticked.Contains(s.Abbr) ? "true" : "false")
.Append(",\"base\":").Append(_base.TryGetValue(s.Abbr, out int b) ? b : -1)
.Append(",\"afford\":").Append(known && c <= budget ? "true" : "false");
Str(sb, "cost", known ? IltParse.Compact(c) : "?");
// By hand (+1 / +10) only the unassigned XP limits, not the raiser's reserve.
long ten = known ? ProjectCost(c, 10) : 0;
sb.Append(",\"known\":").Append(known ? "true" : "false")
.Append(",\"afford1\":").Append(known && c <= have ? "true" : "false")
.Append(",\"afford10\":").Append(known && ten <= have ? "true" : "false");
Str(sb, "cost10", known ? "~" + IltParse.Compact(ten) : "?");
Str(sb, "costFull", known ? IltParse.N0(c) : "");
Str(sb, "cost10Full", known ? IltParse.N0(ten) : "");
sb.Append('}');
}
sb.Append("]}");
}
private static string Ago(long ms)
{
long sec = Math.Max(0, ms / 1000);
return sec < 60 ? $"{sec}s" : sec < 3600 ? $"{sec / 60}m" : $"{sec / 3600}h {sec % 3600 / 60}m";
}
private static void Str(StringBuilder sb, string name, string value, bool first = false)
{
if (!first) sb.Append(',');
sb.Append('"').Append(name).Append("\":\"").Append(RynthAiPlugin.JsonEscape(value ?? string.Empty)).Append('"');
}
/// <summary>"prog attr…" commands from the Skills panel. Returns false when the verb isn't ours.</summary>
public bool HandleRemote(string verb, string[] a)
{
string arg1 = a.Length > 1 ? a[1] : string.Empty;
string arg2 = a.Length > 2 ? a[2] : string.Empty;
switch (verb)
{
case "attrauto":
C.AttrAutoRaise = arg1.Equals("on", StringComparison.OrdinalIgnoreCase);
_nextAutoAtMs = C.AttrAutoRaise ? IltHubContext.NowMs + FirstAutoDelayMs : 0;
if (!C.AttrAutoRaise && Running && _runAuto) Stop("Auto-raise turned off.");
return true;
case "attrevery":
if (int.TryParse(arg1, out int min))
{
C.AttrAutoRaiseMinutes = Math.Clamp(min, 1, 1440);
if (C.AttrAutoRaise) _nextAutoAtMs = IltHubContext.NowMs + C.AttrAutoRaiseMinutes * 60_000L;
}
return true;
case "attrmode":
if (int.TryParse(arg1, out int mode)) C.AttrRaiseMode = Math.Clamp(mode, 0, 2);
return true;
case "attrkeep":
if (arg1.Length == 0 || arg1 == "0") C.AttrKeepXp = 0;
else if (IltParse.TryParseAmount(arg1, out long keep)) C.AttrKeepXp = Math.Max(0, keep);
return true;
case "attron":
{
Stat? s = Find(arg1);
if (s == null) return true;
bool on = arg2.Equals("on", StringComparison.OrdinalIgnoreCase);
C.AttrRaiseStats.RemoveAll(x => x.Equals(s.Abbr, StringComparison.OrdinalIgnoreCase));
if (on) C.AttrRaiseStats.Add(s.Abbr);
return true;
}
case "attrmove":
{
Stat? s = Find(arg1);
if (s == null) return true;
int i = C.AttrOrder.FindIndex(x => x.Equals(s.Abbr, StringComparison.OrdinalIgnoreCase));
int j = arg2.Equals("up", StringComparison.OrdinalIgnoreCase) ? i - 1
: arg2.Equals("top", StringComparison.OrdinalIgnoreCase) ? 0 : i + 1;
if (i < 0 || j < 0 || j >= C.AttrOrder.Count || i == j) return true;
string item = C.AttrOrder[i];
C.AttrOrder.RemoveAt(i);
C.AttrOrder.Insert(j, item);
return true;
}
case "attrorderreset":
C.AttrOrder = new List<string>(DefaultOrder);
return true;
case "attrraise":
if (int.TryParse(arg2, out int levels)) RaiseManual(arg1, levels);
return true;
case "attrrun": Start(auto: false); return true;
case "attrstop": Stop(); return true;
case "attrcosts": RefreshCosts(); return true;
}
return false;
}
}

View file

@ -0,0 +1,224 @@
// IltAugCosts.cs — luminance augmentation cost rules, per server (world name).
//
// Defaults are UB's Leaftide Augs tab (correct for InfiniteLeaftide):
// level i (1-based) costs (Base + (i-1) * Base * LinearPercent/100) * multiplier(i)
// multiplier(i) = M0 below S1, M1 from S1, M2 from S2, M3 from S3, M4 from S4
// (UB: 1 / 4 / 8 / 16 / 24; a tier starts AT its S level).
// Another server can change the multipliers and every aug's base, growth, S1..S4, target cap
// and coins per level from the Progression tab; those edits are saved for that world only in
// one shared file, so every character on the world prices augs the same way.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.Json;
namespace RynthCore.Plugin.RynthAi.IltHub;
/// <summary>The saved file: one cost profile per world that was changed from the defaults.</summary>
public sealed class IltAugCostFile
{
public Dictionary<string, IltAugCostProfile> Servers = new(StringComparer.OrdinalIgnoreCase);
}
/// <summary>A world's cost rules: the five tier multipliers and one row per aug.</summary>
public sealed class IltAugCostProfile
{
public double[] Multipliers = (double[])IltAugCosts.DefaultMultipliers.Clone();
public List<IltAugCostRow> Augs = new();
}
/// <summary>One aug's cost rule. Thresholds are 1-based levels; Cap 0 = no target limit.</summary>
public sealed class IltAugCostRow
{
public string Key = string.Empty;
public long Base;
public double LinearPercent;
public int CoinsPerLevel;
public int S1, S2, S3, S4;
public int Cap;
public IltAugCostRow Clone() => (IltAugCostRow)MemberwiseClone();
}
internal sealed class IltAugCosts
{
/// <summary>UB's tier multipliers: below S1, from S1, from S2, from S3, from S4.</summary>
public static readonly double[] DefaultMultipliers = { 1, 4, 8, 16, 24 };
/// <summary>Highest target the planner accepts when an aug has no cap (keeps the plan sane).</summary>
public const int NoCapLimit = 100_000;
/// <summary>Display order and labels; also the only keys a profile may hold.</summary>
public static readonly (string Key, string Label)[] Labels =
{
("creature", "Creature"), ("item", "Item"), ("life", "Life"), ("war", "War"), ("void", "Void"),
("duration", "Duration"), ("melee", "Melee"), ("missile", "Missile"),
("specialization", "Specialization"), ("summon", "Summon"),
};
/// <summary>UB Augs.cs (ILT): cost models, coins per level and soft caps S1..S4; no target cap.</summary>
public static IltAugCostRow[] DefaultRows() => new[]
{
Row("creature", 750_000, 130, 3, 2750, 4000, 4750, 5250),
Row("item", 1_000_000, 165, 18, 1250, 2000, 3000, 3500),
Row("life", 975_000, 195, 12, 1000, 2000, 3000, 3750),
Row("war", 750_000, 140, 5, 1750, 2500, 3000, 3750),
Row("void", 800_000, 160, 5, 1750, 2500, 3000, 3750),
Row("duration", 400_000, 120, 5, 1000, 2000, 2500, 3000),
Row("melee", 750_000, 140, 5, 1750, 2500, 3000, 3750),
Row("missile", 750_000, 140, 5, 1750, 2500, 3000, 3750),
Row("specialization", 3_000_000, 200, 50, 1750, 2500, 3000, 3750),
Row("summon", 500_000, 125, 36, 1750, 2500, 3000, 3750),
};
private static IltAugCostRow Row(string key, long b, double lp, int coins, int s1, int s2, int s3, int s4)
=> new() { Key = key, Base = b, LinearPercent = lp, CoinsPerLevel = coins, S1 = s1, S2 = s2, S3 = s3, S4 = s4, Cap = 0 };
/// <summary>The shared settings file. Tests point it at a scratch folder before first use.</summary>
public static string FilePath { get; set; } = Path.Combine(IltHubStore.SharedRoot, "ilt-aug-costs.json");
private IltAugCostFile? _file;
private string _lastJson = string.Empty;
private static readonly IltAugCostProfile Defaults = NewDefaultProfile();
public static string Label(string key)
{
foreach (var l in Labels) if (l.Key.Equals(key, StringComparison.OrdinalIgnoreCase)) return l.Label;
return key;
}
private static IltAugCostProfile NewDefaultProfile()
=> new() { Multipliers = (double[])DefaultMultipliers.Clone(), Augs = DefaultRows().ToList() };
private IltAugCostFile File_
{
get
{
if (_file != null) return _file;
_file = new IltAugCostFile();
try
{
if (File.Exists(FilePath))
{
string json = File.ReadAllText(FilePath);
_file = JsonSerializer.Deserialize(json, RynthAiJsonContext.Default.IltAugCostFile) ?? new IltAugCostFile();
_lastJson = json;
}
}
catch (Exception ex) { RynthLog.Exception(LogCat.IltStore, ex, $"load {FilePath}"); _file = new IltAugCostFile(); }
var fixedUp = new Dictionary<string, IltAugCostProfile>(StringComparer.OrdinalIgnoreCase);
foreach (var kv in _file.Servers ?? new())
if (kv.Value != null) fixedUp[kv.Key ?? string.Empty] = Normalize(kv.Value);
_file.Servers = fixedUp;
return _file;
}
}
/// <summary>
/// Repairs a loaded or edited profile: five multipliers, exactly one row per known aug (missing
/// ones from the defaults, unknown ones dropped), non-negative values and S1 &lt;= S2 &lt;= S3 &lt;= S4.
/// </summary>
public static IltAugCostProfile Normalize(IltAugCostProfile p)
{
var m = new double[5];
for (int i = 0; i < 5; i++)
{
double v = p.Multipliers != null && i < p.Multipliers.Length ? p.Multipliers[i] : DefaultMultipliers[i];
m[i] = double.IsFinite(v) ? Math.Clamp(v, 0, 1000) : DefaultMultipliers[i];
}
p.Multipliers = m;
var byKey = new Dictionary<string, IltAugCostRow>(StringComparer.OrdinalIgnoreCase);
foreach (var r in p.Augs ?? new()) if (r != null && !string.IsNullOrEmpty(r.Key)) byKey[r.Key] = r;
var rows = new List<IltAugCostRow>(Labels.Length);
foreach (var def in DefaultRows())
{
var r = byKey.TryGetValue(def.Key, out var have) ? have : def;
r.Key = def.Key;
r.Base = Math.Max(0, r.Base);
r.LinearPercent = double.IsFinite(r.LinearPercent) ? Math.Clamp(r.LinearPercent, 0, 100_000) : def.LinearPercent;
r.CoinsPerLevel = Math.Max(0, r.CoinsPerLevel);
r.S1 = Math.Max(0, r.S1);
r.S2 = Math.Max(r.S1, r.S2);
r.S3 = Math.Max(r.S2, r.S3);
r.S4 = Math.Max(r.S3, r.S4);
r.Cap = Math.Max(0, r.Cap);
rows.Add(r);
}
p.Augs = rows;
return p;
}
/// <summary>The rules for <paramref name="world"/>: its saved profile, or the UB defaults.</summary>
public IltAugCostProfile For(string world)
=> File_.Servers.TryGetValue(world ?? string.Empty, out var p) ? p : Defaults;
/// <summary>True when <paramref name="world"/> has its own saved rules.</summary>
public bool IsCustom(string world) => File_.Servers.ContainsKey(world ?? string.Empty);
/// <summary>Applies an edit to <paramref name="world"/>'s rules (copying the defaults first) and saves.</summary>
public void Edit(string world, Action<IltAugCostProfile> change)
{
string key = world ?? string.Empty;
if (!File_.Servers.TryGetValue(key, out var p))
{
p = NewDefaultProfile();
File_.Servers[key] = p;
}
change(p);
Normalize(p);
Save();
}
/// <summary>Drops <paramref name="world"/>'s saved rules: it goes back to the UB defaults.</summary>
public void Reset(string world)
{
if (File_.Servers.Remove(world ?? string.Empty)) Save();
}
private void Save()
{
try
{
string json = JsonSerializer.Serialize(File_, RynthAiJsonContext.Default.IltAugCostFile);
if (json == _lastJson) return;
Directory.CreateDirectory(Path.GetDirectoryName(FilePath)!);
string tmp = FilePath + ".tmp";
File.WriteAllText(tmp, json);
File.Move(tmp, FilePath, overwrite: true);
_lastJson = json;
}
catch (Exception ex) { RynthLog.Exception(LogCat.IltStore, ex, $"save {FilePath}"); }
}
/// <summary>Highest target the planner allows for <paramref name="r"/> at current level <paramref name="cur"/>.</summary>
public static int Ceiling(IltAugCostRow r, int cur) => Math.Max(cur, r.Cap > 0 ? r.Cap : NoCapLimit);
/// <summary>
/// Luminance for levels cur+1 .. tgt. Same result as UB's per-level loop, summed per tier in
/// closed form: within a tier the per-level base grows linearly, so each tier is an arithmetic series.
/// </summary>
public static decimal LumCost(IltAugCostRow r, double[] mult, int cur, int tgt)
{
int first = Math.Max(1, cur + 1);
if (tgt < first) return 0;
decimal b = r.Base;
decimal step = b * (decimal)r.LinearPercent / 100m;
// Tier t covers levels [lo[t], hi[t]) (1-based); the last tier has no end.
long[] lo = { 1, r.S1, r.S2, r.S3, r.S4 };
long[] hi = { r.S1, r.S2, r.S3, r.S4, long.MaxValue };
decimal total = 0;
for (int t = 0; t < 5; t++)
{
long a = Math.Max(first, lo[t]);
long z = Math.Min(tgt, hi[t] - 1);
if (z < a) continue;
decimal n = z - a + 1;
// sum over i=a..z of (b + (i-1)*step) = n*b + step * sum(i-1) = n*b + step * n*(a-1 + z-1)/2
decimal levels = n * b + step * (n * ((a - 1) + (z - 1)) / 2m);
total += levels * (decimal)mult[t];
}
return total;
}
}

View file

@ -0,0 +1,112 @@
// IltBankCommands.cs — The /bank commands the Banking tab sends, and the reply lines it collects.
//
// Server contract (ACECustom PlayerCommands.HandleBank / Player_Bank, upstream 2026-10-11):
// /b d [code] deposit everything (no code) or one kind; "Deposited N <kind>",
// "No <kind> found to deposit", "Deposited all <kind>!".
// /b lum bank luminance tokens: "Starting Banked Lum", one "Deposited N x <token>"
// a kind, "Ending Banked Lum"; "No luminance tokens found to deposit".
// /b w <code> <amount> withdraw: "Withdrew ...", "You don't have enough ...", "Failed to create ...".
// /b w n <denom> [n] trade notes by denomination (i v x l c d m md mm mmd).
// /b t <code> <n> <who> transfer (IltBanking); Prestige Coins can't be transferred.
// Deposit, withdraw and transfer share one server throttle (bank_command_limit); a plain
// /bank balance doesn't touch it. Pure: no host calls, so the host tests cover it.
using System;
namespace RynthCore.Plugin.RynthAi.IltHub;
internal static class IltBankCommands
{
/// <summary>A deposit choice: label, and the command's argument after "/b d" ("" = all).</summary>
public static readonly (string Label, string Args)[] Deposits =
{
("Everything", ""),
("Pyreals", "p"),
("Pyreal peas", "ps"),
("Luminance", "l"),
("Luminance tokens", "lum"),
("Legendary keys", "k"),
("Mythical keys", "mk"),
("Enlightened coins", "e"),
("Weakly enlightened coins", "we"),
("Prestige coins", "pc"),
("Trade notes", "n"),
};
/// <summary>A withdraw choice: label and the server code; "n" is trade notes (by denomination).</summary>
public static readonly (string Label, string Code)[] Withdrawals =
{
("Pyreals", "p"),
("Luminance", "l"),
("Legendary keys", "k"),
("Mythical keys", "mk"),
("Enlightened coins", "e"),
("Weakly enlightened coins", "we"),
("Prestige coins", "pc"),
("Trade notes", "n"),
};
/// <summary>Trade note denominations: label and code, in the server's order.</summary>
public static readonly (string Label, string Code, long Value)[] NoteDenominations =
{
("I (100)", "i", 100), ("V (500)", "v", 500), ("X (1K)", "x", 1_000), ("L (5K)", "l", 5_000),
("C (10K)", "c", 10_000), ("D (50K)", "d", 50_000), ("M (100K)", "m", 100_000),
("MD (150K)", "md", 150_000), ("MM (200K)", "mm", 200_000), ("MMD (250K)", "mmd", 250_000),
};
/// <summary>The server refuses a trade-note withdrawal of more than this many notes.</summary>
public const int MaxNoteCount = 50_000;
/// <summary>"/b d", "/b d p", or "/b lum" for the luminance tokens; empty for an unknown index.</summary>
public static string Deposit(int index)
{
if (index < 0 || index >= Deposits.Length) return string.Empty;
string args = Deposits[index].Args;
if (args.Length == 0) return "/b d";
return args == "lum" ? "/b lum" : "/b d " + args;
}
/// <summary>
/// "/b w p 1000000", or "/b w n mmd 5" for trade notes (<paramref name="amount"/> is then the
/// note count). Empty (with <paramref name="error"/>) when the input can't be sent.
/// </summary>
public static string Withdraw(int index, long amount, int denomination, out string error)
{
error = string.Empty;
if (index < 0 || index >= Withdrawals.Length) { error = "Pick what to withdraw."; return string.Empty; }
if (amount <= 0) { error = "Amount must be positive."; return string.Empty; }
string code = Withdrawals[index].Code;
if (code != "n") return $"/b w {code} {amount}";
if (denomination < 0 || denomination >= NoteDenominations.Length) { error = "Pick a note denomination."; return string.Empty; }
if (amount > MaxNoteCount) { error = $"At most {MaxNoteCount:N0} notes at a time."; return string.Empty; }
return $"/b w n {NoteDenominations[denomination].Code} {amount}";
}
/// <summary>
/// True for a line the server sends in reply to a deposit or withdrawal (so the tab can show
/// it as the result). Only lines the bank code writes; never "[BANK]" balance lines.
/// </summary>
public static bool IsActionReply(string line)
{
if (string.IsNullOrEmpty(line)) return false;
return line.StartsWith("Deposited ", StringComparison.Ordinal)
|| line.StartsWith("Withdrew ", StringComparison.Ordinal)
|| (line.StartsWith("No ", StringComparison.Ordinal) && line.EndsWith("to deposit", StringComparison.Ordinal))
|| line.StartsWith("Starting Banked Lum", StringComparison.Ordinal)
|| line.StartsWith("Ending Banked Lum", StringComparison.Ordinal)
|| line.StartsWith("Not deposited", StringComparison.Ordinal)
|| line.StartsWith("You don't have enough", StringComparison.Ordinal)
|| line.StartsWith("You cannot hold any more", StringComparison.Ordinal)
|| line.StartsWith("You have not been luminance flagged", StringComparison.Ordinal)
|| line.StartsWith("Failed to ", StringComparison.Ordinal)
|| line.StartsWith("Warning: Requested", StringComparison.Ordinal)
|| line.StartsWith("Amount must be", StringComparison.Ordinal)
|| line.StartsWith("Cannot deposit while", StringComparison.Ordinal)
|| line.StartsWith("[Deposit]", StringComparison.Ordinal)
|| line.StartsWith("[Withdraw]", StringComparison.Ordinal)
|| line.StartsWith("Invalid amount", StringComparison.Ordinal)
|| line.StartsWith("Invalid denomination", StringComparison.Ordinal)
|| line.StartsWith("Count must be", StringComparison.Ordinal)
|| line.StartsWith("Count cannot exceed", StringComparison.Ordinal)
|| line.StartsWith("You are not permitted to use bank commands", StringComparison.Ordinal);
}
}

View file

@ -0,0 +1,572 @@
// IltBanking.cs — ILT Hub "Banking" tab: /bank balances, deposits, withdrawals, confirmed
// transfers, transaction log.
//
// Server contract (ACECustom PlayerCommands bank handler, upstream 2026-10-11):
// /bank → "[BANK] Your balances are:" then "[BANK] Pyreals: N", "Luminance:",
// "Legendary Keys:", "Mythical Keys:", "Enlightened Coins:",
// "Weakly Enlightened Coins:", "Prestige Coins: N (bound to you ...)".
// /b d, /b lum, /b w → deposits and withdrawals (IltBankCommands has the commands and replies).
// /bank t <c> <n> <who> → "Transferred {N0} {Currency} to {Name}[ (offline)]" or an error;
// the recipient sees "Received {N0} {currency} from {Name}".
// Codes: p pyreals, l luminance, k legendary keys, mk mythical keys, e enl coins, we weak coins.
// Prestige Coins (pc) are bound: deposit and withdraw only.
// Deposit, withdraw and transfer share the server's bank_command_limit throttle; a balance
// refresh doesn't, so it has its own (client-side) spacing.
// Balance lines are parsed whenever they appear (player-typed /bank too) but only EATEN
// when the Hub asked. Transfers always need a confirmation (UB had none).
using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
using ImGuiNET;
using RynthCore.Plugin.RynthAi.LegacyUi;
namespace RynthCore.Plugin.RynthAi.IltHub;
internal sealed class IltBanking : IIltFeature
{
/// <summary>Transfer currency table: display name, /bank t code.</summary>
public static readonly (string Name, string Code)[] Currencies =
{
("Pyreals", "p"),
("Luminance", "l"),
("Legendary Keys", "k"),
("Mythical Keys", "mk"),
("Enlightened Coins", "e"),
("Weakly Enlightened Coins", "we"),
};
private static readonly string[] CurrencyNames = Currencies.Select(c => c.Name).ToArray();
private static readonly string[] DepositNames = IltBankCommands.Deposits.Select(d => d.Label).ToArray();
private static readonly string[] WithdrawNames = IltBankCommands.Withdrawals.Select(w => w.Label).ToArray();
private static readonly string[] NoteNames = IltBankCommands.NoteDenominations.Select(n => n.Label).ToArray();
/// <summary>Server throttle for deposit / withdraw / transfer (bank_command_limit).</summary>
private const long BankCommandSpacingMs = 5000;
/// <summary>Client spacing for balance refreshes (the server doesn't throttle a plain /bank).</summary>
private const long BalanceSpacingMs = 5000;
/// <summary>After a deposit or withdrawal, the balances are re-read this long after the reply.</summary>
private const long RefreshAfterActionMs = 1500;
private readonly IltHubContext _ctx;
private readonly object _txLock = new();
private readonly List<IltBankTransaction> _transactions;
private IltBankTransaction[] _txSnapshot = Array.Empty<IltBankTransaction>();
private bool _txDirty;
private long _lastBankCommandAt;
private long _lastBalanceAt;
private long _lastAutoRefreshAt;
/// <summary>When a quiet balance refresh is due after an action (0 = none). Pump thread.</summary>
private long _refreshDueAt;
/// <summary>Until then, money is moving between pack and bank (MovingMoney). Pump thread.</summary>
private long _moveUntil;
/// <summary>How long after a deposit / withdrawal reply the moved amounts are not income (covers the balance re-read).</summary>
private const long MoveWindowMs = 12_000;
// Render-thread form state.
private string _amountText = string.Empty;
private string _withdrawText = string.Empty;
private string _txFilter = string.Empty;
private string _lastResult = string.Empty;
private volatile string _actionResult = string.Empty;
/// <summary>Raised (pump thread) after a balance line updates the state; Character rates use the deltas.</summary>
public event Action<string, long, long>? BalanceChanged;
public IltBanking(IltHubContext ctx)
{
_ctx = ctx;
_transactions = ctx.Store.LoadTransactions();
PublishSnapshot();
}
private IltBankState Bank => _ctx.State.Bank;
public bool Enabled => _ctx.Options.IsOn(IltFeature.Bank);
/// <summary>
/// True while a deposit or withdrawal is moving money between the pack and the bank (sent from
/// this tab or typed): session rates then re-baseline instead of counting it as income. Pump thread.
/// </summary>
public bool MovingMoney => IltHubContext.NowMs < _moveUntil;
/// <summary>Exposed for the one-time UB import (mutated under the lock).</summary>
public void ImportUb(Func<List<IltBankTransaction>, string> importer)
{
string summary;
lock (_txLock)
{
summary = importer(_transactions);
_txDirty = true;
}
PublishSnapshot();
RynthLog.Write(LogCat.IltBanking, $"[IltHub] UB sidecar import: {summary}");
}
// ── Commands ────────────────────────────────────────────────────────────
/// <summary>Queues a /bank balance refresh (eaten when <paramref name="quiet"/>).</summary>
public void RequestRefresh(bool quiet)
{
RynthLog.Trace(LogCat.IltBanking, $"RequestRefresh(quiet={quiet})");
if (_ctx.Capture.IsPending("/bank")) return;
long now = IltHubContext.NowMs;
if (now - _lastBalanceAt < BalanceSpacingMs) return;
_lastBalanceAt = now;
_ctx.Capture.Enqueue(new IltChatRequest
{
Command = "/bank",
IsResponseLine = t => t.StartsWith("[BANK]", StringComparison.OrdinalIgnoreCase),
IdleEndMs = 2000,
FirstLineTimeoutMs = 15000,
Eat = quiet,
OnComplete = r =>
{
if (r.UnknownCommand) _ctx.Options.Set(IltFeature.Bank, IltTri.Off);
else if (r.Lines.Count > 0) _ctx.Options.Set(IltFeature.Bank, IltTri.On);
},
});
}
/// <summary>
/// Validates and (after the UI confirm) sends a transfer. Pump thread.
/// Returns an error message, or empty when the command was queued.
/// </summary>
public string SendTransfer(int currencyIndex, long amount, string target)
{
RynthLog.Trace(LogCat.IltBanking, $"SendTransfer(currency={currencyIndex}, amount={amount}, target='{target}')");
if (!Enabled) return "Bank is not available on this server.";
if (currencyIndex < 0 || currencyIndex >= Currencies.Length) return "Pick a currency.";
if (amount <= 0) return "Amount must be positive.";
target = (target ?? string.Empty).Trim();
if (target.Length == 0) return "Enter a recipient.";
// The recipient is spliced into a chat command, so only character-name characters are
// allowed: no '/', control characters or line breaks that could start a second command.
if (!IltParse.CharacterName.IsMatch(target)) return "Recipient must be a character name (letters, spaces, ' and - only).";
if (target.Equals(_ctx.CharName, StringComparison.OrdinalIgnoreCase)) return "You cannot transfer to yourself.";
long now = IltHubContext.NowMs;
if (now - _lastBankCommandAt < BankCommandSpacingMs) return "Bank commands are limited to one every 5 seconds.";
_lastBankCommandAt = now;
string cmd = $"/bank t {Currencies[currencyIndex].Code} {amount} {target}";
_ctx.Capture.Enqueue(new IltChatRequest
{
Command = cmd,
IsResponseLine = t => t.StartsWith("Transferred ", StringComparison.Ordinal)
|| t.StartsWith("Character '", StringComparison.Ordinal)
|| t.StartsWith("You cannot transfer", StringComparison.Ordinal)
|| t.StartsWith("You don't have enough", StringComparison.Ordinal)
|| t.StartsWith("[Transfer]", StringComparison.Ordinal),
IdleEndMs = 500,
FirstLineTimeoutMs = 8000,
Eat = false,
OnComplete = r =>
{
_lastResult = r.Lines.Count > 0 ? r.Lines[^1] : (r.TimedOut ? "No reply from server." : string.Empty);
// Balances changed: read them again shortly.
_refreshDueAt = IltHubContext.NowMs + RefreshAfterActionMs;
},
});
return string.Empty;
}
/// <summary>
/// Sends a deposit (<see cref="IltBankCommands.Deposits"/> index). Pump thread. Returns an
/// error message, or empty when the command was queued; the reply lands in the tab.
/// </summary>
public string SendDeposit(int index)
{
string cmd = IltBankCommands.Deposit(index);
if (cmd.Length == 0) return "Pick what to deposit.";
return SendAction(cmd, "Deposit");
}
/// <summary>
/// Sends a withdrawal (<see cref="IltBankCommands.Withdrawals"/> index; for trade notes
/// <paramref name="amount"/> is the note count). Pump thread; same result as SendDeposit.
/// </summary>
public string SendWithdraw(int index, long amount, int denomination)
{
string cmd = IltBankCommands.Withdraw(index, amount, denomination, out string error);
if (cmd.Length == 0) return error;
return SendAction(cmd, "Withdraw");
}
/// <summary>A deposit or withdrawal through the capture queue (shown, not eaten), then a quiet balance read.</summary>
private string SendAction(string cmd, string what)
{
RynthLog.Trace(LogCat.IltBanking, $"{what}: '{cmd}'");
if (!Enabled) return "Bank is not available on this server.";
long now = IltHubContext.NowMs;
if (now - _lastBankCommandAt < BankCommandSpacingMs) return "Bank commands are limited to one every 5 seconds.";
_lastBankCommandAt = now;
_moveUntil = now + MoveWindowMs;
_actionResult = what + " sent...";
_ctx.Capture.Enqueue(new IltChatRequest
{
Command = cmd,
IsResponseLine = IltBankCommands.IsActionReply,
IdleEndMs = 800,
FirstLineTimeoutMs = 8000,
Eat = false,
OnComplete = r =>
{
_actionResult = r.Lines.Count > 0 ? string.Join("\n", r.Lines.TakeLast(6))
: r.TimedOut ? "No reply from the server." : string.Empty;
_refreshDueAt = IltHubContext.NowMs + RefreshAfterActionMs;
},
});
return string.Empty;
}
// ── IIltFeature ─────────────────────────────────────────────────────────
public void Tick(long nowMs)
{
// Periodic quiet refresh only while the Hub is open and the server has /bank.
int every = Bank.AutoRefreshSeconds;
if (Enabled && _ctx.WindowOpen && every > 0 && nowMs - _lastAutoRefreshAt >= every * 1000L
&& nowMs - _lastBalanceAt >= BalanceSpacingMs)
{
_lastAutoRefreshAt = nowMs;
RequestRefresh(quiet: true);
}
// The balance read a deposit, withdrawal or transfer asked for (retried until the spacing allows).
if (_refreshDueAt != 0 && nowMs >= _refreshDueAt && Enabled && nowMs - _lastBalanceAt >= BalanceSpacingMs)
{
_refreshDueAt = 0;
_lastAutoRefreshAt = nowMs;
RequestRefresh(quiet: true);
}
if (_txDirty)
{
lock (_txLock)
{
_ctx.Store.SaveTransactionsIfDirty(_transactions);
_txDirty = false;
}
PublishSnapshot();
}
}
public bool OnChat(string text)
{
if (text.StartsWith("[BANK]", StringComparison.OrdinalIgnoreCase))
{
ParseBalanceLine(text);
return false; // eating is decided by the capture queue
}
// A deposit or withdrawal reply (ours or a typed /b): the next balance and pack changes are moves.
if (text.StartsWith("Deposited ", StringComparison.Ordinal) || text.StartsWith("Withdrew ", StringComparison.Ordinal))
_moveUntil = Math.Max(_moveUntil, IltHubContext.NowMs + MoveWindowMs);
TryLogTransaction(text);
return false;
}
public void OnLogout()
{
lock (_txLock) _ctx.Store.SaveTransactionsIfDirty(_transactions);
}
// ── Parsing ─────────────────────────────────────────────────────────────
private void ParseBalanceLine(string text)
{
string body = text.Substring("[BANK]".Length).Trim();
int colon = body.IndexOf(':');
if (colon <= 0) return;
string label = body.Substring(0, colon).Trim();
long value = IltParse.ParseLeadingLong(body.Substring(colon + 1));
if (body.Substring(colon + 1).Trim().Length == 0) return; // header "Your balances are:"
// Order matters: "Weakly Enlightened Coins" also contains "Enlightened Coins".
if (label.Contains("Prestige", StringComparison.OrdinalIgnoreCase)) Apply("PrestigeCoins", ref Bank.PrestigeCoins, value);
else if (label.Contains("Weakly", StringComparison.OrdinalIgnoreCase)) Apply("WeaklyEnlightenedCoins", ref Bank.WeaklyEnlightenedCoins, value);
else if (label.Contains("Enlightened", StringComparison.OrdinalIgnoreCase)) Apply("EnlightenedCoins", ref Bank.EnlightenedCoins, value);
else if (label.Contains("Mythical", StringComparison.OrdinalIgnoreCase)) Apply("MythicalKeys", ref Bank.MythicalKeys, value);
else if (label.Contains("Legendary", StringComparison.OrdinalIgnoreCase)) Apply("LegendaryKeys", ref Bank.LegendaryKeys, value);
else if (label.Contains("Luminance", StringComparison.OrdinalIgnoreCase)) Apply("Luminance", ref Bank.Luminance, value);
else if (label.Contains("Pyreal", StringComparison.OrdinalIgnoreCase)) Apply("Pyreals", ref Bank.Pyreals, value);
else return;
Bank.LastUpdated = DateTime.Now;
_ctx.Options.Set(IltFeature.Bank, IltTri.On);
}
private void Apply(string key, ref long field, long value)
{
long old = field;
field = value;
if (old != value)
{
try { BalanceChanged?.Invoke(key, old, value); } catch { }
}
}
private void TryLogTransaction(string text)
{
if (!(text.StartsWith("Transferred ", StringComparison.Ordinal) || text.StartsWith("Received ", StringComparison.Ordinal)))
return;
// Only server system lines are logged. Anything another player can author (tells, says,
// emotes, any bracketed channel) is rejected so quoted "Transferred ..." text can't
// forge entries in the transaction log.
if (IsPlayerAuthoredLine(text))
{
RynthLog.Trace(LogCat.IltBanking, "transaction ignored (player-authored line): " + text);
return;
}
var sent = IltParse.BankSent.Match(text);
var recv = sent.Success ? System.Text.RegularExpressions.Match.Empty : IltParse.BankReceived.Match(text);
var m = sent.Success ? sent : recv;
if (!m.Success) return;
string other = IltParse.StripMarkup(m.Groups[3].Value).Replace(" (offline)", string.Empty).Trim();
var tx = new IltBankTransaction
{
Timestamp = DateTime.Now,
Type = sent.Success ? "Sent" : "Received",
Amount = IltParse.ParseLeadingLong(m.Groups[1].Value),
Currency = m.Groups[2].Value.Trim(),
OtherPlayer = other,
Description = text,
};
lock (_txLock)
{
_transactions.Add(tx);
if (_transactions.Count > IltHubStore.MaxTransactions)
_transactions.RemoveRange(0, _transactions.Count - IltHubStore.MaxTransactions);
_txDirty = true;
}
}
/// <summary>True for chat another player could have written (tells, says, channel or emote markup).</summary>
private static bool IsPlayerAuthoredLine(string text)
=> text.Contains("<Tell:", StringComparison.Ordinal)
|| text.Contains(" tells you", StringComparison.Ordinal)
|| text.Contains(" says, \"", StringComparison.Ordinal)
|| text.Contains("[Allegiance]", StringComparison.Ordinal)
|| text.Contains("[Fellowship]", StringComparison.Ordinal)
|| text.Contains("[General]", StringComparison.Ordinal)
|| text.Contains("[Trade]", StringComparison.Ordinal)
|| text.Contains("[LFG]", StringComparison.Ordinal)
|| text.Contains("[Roleplay]", StringComparison.Ordinal)
|| text.Contains("[Society]", StringComparison.Ordinal)
|| text.Contains("[Olthoi]", StringComparison.Ordinal)
|| text.Contains("[Patron]", StringComparison.Ordinal)
|| text.Contains("[Vassals]", StringComparison.Ordinal)
|| text.Contains("[Covassals]", StringComparison.Ordinal)
|| text.Contains("[Monarch]", StringComparison.Ordinal);
private void PublishSnapshot()
{
lock (_txLock) _txSnapshot = _transactions.ToArray();
}
// ── UI (render thread) ──────────────────────────────────────────────────
public void Render()
{
if (!Enabled)
{
ImGui.TextColored(LegacyDashboardRenderer.ColTextMute,
_ctx.Options.IsOff(IltFeature.Bank) ? "The server reports /bank is not available." : "Waiting for the server options check...");
return;
}
// Balances
ImGui.TextColored(LegacyDashboardRenderer.ColTeal, "Balances");
ImGui.SameLine();
if (ImGui.SmallButton("Refresh##bank")) _ctx.Post(() => RequestRefresh(quiet: true));
ImGui.SameLine();
if (ImGui.SmallButton("Copy##bank")) ImGui.SetClipboardText(BuildCopyLine());
ImGui.SameLine();
ImGui.TextDisabled(Bank.LastUpdated == DateTime.MinValue ? "never updated" : "updated " + Bank.LastUpdated.ToString("g"));
if (ImGui.BeginTable("##iltbal", 2, ImGuiTableFlags.RowBg | ImGuiTableFlags.BordersInnerV))
{
Row("Pyreals", Bank.Pyreals);
Row("Luminance", Bank.Luminance);
Row("Legendary Keys", Bank.LegendaryKeys);
Row("Mythical Keys", Bank.MythicalKeys);
Row("Enlightened Coins", Bank.EnlightenedCoins);
Row("Weakly Enlightened Coins", Bank.WeaklyEnlightenedCoins);
Row("Prestige Coins", Bank.PrestigeCoins);
if (ImGui.IsItemHovered()) ImGui.SetTooltip("Bound to you: deposit and withdraw only, never transferred.");
ImGui.EndTable();
}
int refresh = Bank.AutoRefreshSeconds;
ImGui.SetNextItemWidth(120);
if (ImGui.InputInt("Auto-refresh seconds (0 = off)", ref refresh, 30))
Bank.AutoRefreshSeconds = refresh <= 0 ? 0 : Math.Max(30, refresh);
ImGui.Separator();
RenderDepositWithdraw();
ImGui.Separator();
RenderTransferForm();
ImGui.Separator();
RenderTransactionLog();
}
private static void Row(string label, long value)
{
ImGui.TableNextRow();
ImGui.TableNextColumn();
ImGui.TextUnformatted(label);
ImGui.TableNextColumn();
ImGui.TextUnformatted($"{IltParse.N0(value)} ({IltParse.Compact(value)})");
}
/// <summary>Deposit (one kind or everything, luminance tokens included) and withdraw (an amount, or trade notes).</summary>
private void RenderDepositWithdraw()
{
ImGui.TextColored(LegacyDashboardRenderer.ColTeal, "Deposit");
int dep = Math.Clamp(Bank.DepositIndex, 0, DepositNames.Length - 1);
ImGui.SetNextItemWidth(200);
if (ImGui.Combo("##bankdep", ref dep, DepositNames, DepositNames.Length)) Bank.DepositIndex = dep;
ImGui.SameLine();
if (ImGui.Button("Deposit##bankdep"))
{
int index = dep;
_ctx.Post(() => { string err = SendDeposit(index); if (err.Length > 0) _actionResult = err; });
}
if (ImGui.IsItemHovered())
ImGui.SetTooltip(IltBankCommands.Deposit(dep) + "\nEverything banks all currencies, notes and luminance tokens."
+ "\nThe server refuses while you are busy or moving.");
ImGui.TextColored(LegacyDashboardRenderer.ColTeal, "Withdraw");
int wd = Math.Clamp(Bank.WithdrawIndex, 0, WithdrawNames.Length - 1);
ImGui.SetNextItemWidth(200);
if (ImGui.Combo("##bankwd", ref wd, WithdrawNames, WithdrawNames.Length)) Bank.WithdrawIndex = wd;
bool notes = IltBankCommands.Withdrawals[wd].Code == "n";
int denom = Math.Clamp(Bank.WithdrawNoteIndex, 0, NoteNames.Length - 1);
if (notes)
{
ImGui.SameLine();
ImGui.SetNextItemWidth(110);
if (ImGui.Combo("##bankwdnote", ref denom, NoteNames, NoteNames.Length)) Bank.WithdrawNoteIndex = denom;
}
ImGui.SetNextItemWidth(200);
ImGui.InputTextWithHint("##bankwdamt", notes ? "how many notes" : "amount, e.g. 250000, 1.5m", ref _withdrawText, 32u);
bool ok = IltParse.TryParseAmount(_withdrawText, out long amount);
ImGui.SameLine();
ImGui.BeginDisabled(!ok);
if (ImGui.Button("Withdraw##bankwd"))
{
int index = wd, note = denom;
long amt = amount;
_ctx.Post(() => { string err = SendWithdraw(index, amt, note); if (err.Length > 0) _actionResult = err; });
}
ImGui.EndDisabled();
if (_withdrawText.Length > 0)
{
ImGui.SameLine();
if (!ok) ImGui.TextColored(LegacyDashboardRenderer.ColHp, "invalid amount");
else if (notes) ImGui.TextDisabled("= " + IltParse.N0(amount * IltBankCommands.NoteDenominations[denom].Value) + " pyreals");
else ImGui.TextDisabled("= " + IltParse.N0(amount));
}
string result = _actionResult;
if (result.Length > 0) ImGui.TextWrapped(result);
}
private void RenderTransferForm()
{
ImGui.TextColored(LegacyDashboardRenderer.ColTeal, "Transfer");
int idx = Math.Clamp(Bank.TransferCurrencyIndex, 0, Currencies.Length - 1);
ImGui.SetNextItemWidth(200);
if (ImGui.Combo("Currency##xfer", ref idx, CurrencyNames, CurrencyNames.Length))
Bank.TransferCurrencyIndex = idx;
ImGui.SetNextItemWidth(200);
ImGui.InputTextWithHint("Amount##xfer", "e.g. 250000, 1.5m, 2b", ref _amountText, 32u);
string target = Bank.TransferTarget;
ImGui.SetNextItemWidth(200);
if (ImGui.InputTextWithHint("Recipient##xfer", "character name", ref target, 64u))
Bank.TransferTarget = target;
bool amountOk = IltParse.TryParseAmount(_amountText, out long amount);
if (_amountText.Length > 0)
{
ImGui.SameLine();
if (amountOk) ImGui.TextDisabled("= " + IltParse.N0(amount));
else ImGui.TextColored(LegacyDashboardRenderer.ColHp, "invalid amount");
}
ImGui.BeginDisabled(!amountOk || string.IsNullOrWhiteSpace(Bank.TransferTarget));
if (ImGui.Button("Send transfer..."))
{
int cur = idx;
long amt = amount;
string who = Bank.TransferTarget.Trim();
_ctx.Confirm("Confirm bank transfer",
$"Send {IltParse.N0(amt)} {Currencies[cur].Name} to {who}?\n\nThis cannot be undone.",
() =>
{
string err = SendTransfer(cur, amt, who);
_lastResult = err.Length > 0 ? err : "Transfer sent...";
},
"Send");
}
ImGui.EndDisabled();
if (_lastResult.Length > 0) ImGui.TextWrapped(_lastResult);
}
private void RenderTransactionLog()
{
var snap = _txSnapshot;
ImGui.TextColored(LegacyDashboardRenderer.ColTeal, $"Transactions ({snap.Length})");
ImGui.SameLine();
ImGui.SetNextItemWidth(180);
ImGui.InputTextWithHint("##txfilter", "filter player / currency", ref _txFilter, 64u);
ImGui.SameLine();
if (ImGui.SmallButton("Copy CSV")) ImGui.SetClipboardText(BuildCsv(snap));
if (ImGui.BeginTable("##ilttx", 5, ImGuiTableFlags.RowBg | ImGuiTableFlags.ScrollY | ImGuiTableFlags.BordersInnerV | ImGuiTableFlags.Resizable,
new Vector2(0, 220)))
{
ImGui.TableSetupScrollFreeze(0, 1);
ImGui.TableSetupColumn("When");
ImGui.TableSetupColumn("Type");
ImGui.TableSetupColumn("Amount");
ImGui.TableSetupColumn("Currency");
ImGui.TableSetupColumn("Player");
ImGui.TableHeadersRow();
for (int i = snap.Length - 1; i >= 0; i--)
{
var t = snap[i];
if (_txFilter.Length > 0
&& !t.OtherPlayer.Contains(_txFilter, StringComparison.OrdinalIgnoreCase)
&& !t.Currency.Contains(_txFilter, StringComparison.OrdinalIgnoreCase))
continue;
ImGui.TableNextRow();
ImGui.TableNextColumn(); ImGui.TextUnformatted(t.Timestamp.ToString("g"));
ImGui.TableNextColumn();
ImGui.TextColored(t.Type == "Sent" ? LegacyDashboardRenderer.ColAmber : LegacyDashboardRenderer.ColGreen, t.Type);
ImGui.TableNextColumn(); ImGui.TextUnformatted(IltParse.N0(t.Amount));
ImGui.TableNextColumn(); ImGui.TextUnformatted(t.Currency);
ImGui.TableNextColumn(); ImGui.TextUnformatted(t.OtherPlayer);
}
ImGui.EndTable();
}
}
/// <summary>One-line summary in UB's chat-paste format.</summary>
public string BuildCopyLine()
=> $"Bank Balances - {_ctx.CharName} | P: {IltParse.N0(Bank.Pyreals)} | L: {IltParse.N0(Bank.Luminance)} | "
+ $"LK: {IltParse.N0(Bank.LegendaryKeys)} | MK: {IltParse.N0(Bank.MythicalKeys)} | "
+ $"Coins: {IltParse.N0(Bank.EnlightenedCoins)} | W Coins: {IltParse.N0(Bank.WeaklyEnlightenedCoins)} | "
+ $"P Coins: {IltParse.N0(Bank.PrestigeCoins)} | "
+ $"Updated: {(Bank.LastUpdated == DateTime.MinValue ? "never" : Bank.LastUpdated.ToString("g"))}";
private static string BuildCsv(IltBankTransaction[] rows)
{
var sb = new System.Text.StringBuilder("Timestamp,Type,Amount,Currency,Player\n");
foreach (var t in rows)
sb.Append(t.Timestamp.ToString("s")).Append(',').Append(t.Type).Append(',').Append(t.Amount).Append(',')
.Append('"').Append(t.Currency.Replace("\"", "\"\"")).Append("\",\"")
.Append(t.OtherPlayer.Replace("\"", "\"\"")).Append("\"\n");
return sb.ToString();
}
}

View file

@ -0,0 +1,254 @@
// IltBuffKeepers.cs — Rune-of-Dispel auto-dispel and Surging Strength keeper (Gear tab).
//
// Both read the player's enchantment list once a second (one shared read).
// Dispel: classifies active spells by NAME (SpellDatabase has no debuff flag):
// 1. Mire Foot (3051 / "mire"+"foot") → never (dispelling it is pointless)
// 2. user include list → dispel
// 3. beneficial pattern → keep
// 4. user exclude list → keep
// 5. known-harmful exact name or pattern → dispel
// and uses a Rune of Dispel (WCID 30133). Cooldown, verify after 2 s, up to 3 retries.
// Surging Strength: uses the Empowered Volcanic Ember when the buff is missing.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using ImGuiNET;
using RynthCore.Plugin.RynthAi.LegacyUi;
namespace RynthCore.Plugin.RynthAi.IltHub;
internal sealed class IltBuffKeepers : IIltFeature
{
private const int SpellMireFoot = 3051;
private const int MaxEnch = 256;
private static readonly HashSet<string> HarmfulExact = BuildHarmfulExact();
private static readonly Regex HarmfulPattern = new(
@"\b(vulnerability|imperil|weakness|slowness|bane|exhaustion|mana burn|fester|curse of|blight of|burden of)\b",
RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
private static readonly Regex BeneficialPattern = new(
@"\b(invulnerability|invulnerable|protection|ward|armor|blessing|strength|coordination|endurance|quickness|focus|willpower|"
+ @"regeneration|mana renewal|stamina renewal|health renewal|arcanum|cantrap|enhancement|augmentation|weave of|shroud of|"
+ @"mantle of|cloak of|veil of|master's blessing|society|fellowship|loyalty|devotion)\b",
RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
private static HashSet<string> BuildHarmfulExact()
{
var set = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
foreach (string s in new[] { "weakness other", "vulnerability other", "imperil other", "slowness other",
"bane other", "exhaustion other", "mana burn other", "fester other" })
{
set.Add(s);
set.Add("incantation of " + s);
}
foreach (string s in new[] { "belly of lead", "gelidite's gift", "inferno's gift", "senescence", "archer's gift",
"swordsman's gift", "leaden feet", "heart of ice", "burning soul", "withering" })
set.Add(s);
return set;
}
private readonly IltHubContext _ctx;
private readonly uint[] _ids = new uint[MaxEnch];
private readonly double[] _exp = new double[MaxEnch];
private long _lastRead;
// Dispel state
private long _dispelCooldownUntil;
private long _verifyAt;
private int _retries;
private volatile string[] _harmfulNow = Array.Empty<string>();
private volatile string _dispelStatus = "idle";
// Surging state
private long _surgeCooldownUntil;
private volatile bool _surgeActive;
private volatile string _surgeStatus = "idle";
// Render-thread edit buffers
private string _newInclude = string.Empty, _newExclude = string.Empty;
public IltBuffKeepers(IltHubContext ctx) => _ctx = ctx;
private IltGearState G => _ctx.State.Gear;
/// <summary>True when this spell should be dispelled (precedence documented above).</summary>
public bool IsHarmful(int spellId, string name)
{
if (spellId == SpellMireFoot || (name.Contains("mire", StringComparison.OrdinalIgnoreCase) && name.Contains("foot", StringComparison.OrdinalIgnoreCase)))
return false;
if (G.DispelInclusions.ToArray().Any(i => i.Length > 0 && name.Contains(i, StringComparison.OrdinalIgnoreCase))) return true;
if (BeneficialPattern.IsMatch(name)) return false;
if (G.DispelExclusions.ToArray().Any(e => e.Length > 0 && name.Contains(e, StringComparison.OrdinalIgnoreCase))) return false;
string bare = StripTier(name);
return HarmfulExact.Contains(name) || HarmfulExact.Contains(bare) || HarmfulPattern.IsMatch(name);
}
/// <summary>"Vulnerability Other VII" → "vulnerability other" (roman numeral suffix removed).</summary>
private static string StripTier(string name)
{
string n = name.Trim();
int sp = n.LastIndexOf(' ');
if (sp > 0)
{
string tail = n.Substring(sp + 1);
if (tail.Length > 0 && tail.All(ch => "IVXL".IndexOf(char.ToUpperInvariant(ch)) >= 0)) n = n.Substring(0, sp);
}
return n.ToLowerInvariant();
}
private WorldObject? FindRune()
=> _ctx.Inventory.FindByWcid(IltInventory.WcidRuneOfDispel)
?? _ctx.Inventory.FindByName(n => n.Equals("Rune of Dispel", StringComparison.OrdinalIgnoreCase)
|| (n.Contains("dispel", StringComparison.OrdinalIgnoreCase) && n.Contains("rune", StringComparison.OrdinalIgnoreCase)));
private WorldObject? FindEmber()
=> _ctx.Inventory.FindByName(n => n.Contains("empowered", StringComparison.OrdinalIgnoreCase)
&& n.Contains("volcanic", StringComparison.OrdinalIgnoreCase)
&& n.Contains("ember", StringComparison.OrdinalIgnoreCase));
// ── IIltFeature ─────────────────────────────────────────────────────────
public void Tick(long nowMs)
{
if (!G.AutoDispel && !G.SurgingStrength) return;
if (nowMs - _lastRead < 1000) return;
_lastRead = nowMs;
if (!_ctx.Host.HasReadPlayerEnchantments) return;
int n = _ctx.Host.ReadPlayerEnchantments(_ids, _exp, MaxEnch);
if (n < 0) return;
n = Math.Min(n, MaxEnch);
var harmful = new List<string>();
bool surge = false;
for (int i = 0; i < n; i++)
{
int id = unchecked((int)_ids[i]);
string name = SpellDatabase.GetSpellName(id);
if (string.IsNullOrEmpty(name)) continue;
if (name.Contains("Surging Strength", StringComparison.OrdinalIgnoreCase)) surge = true;
if (G.AutoDispel && IsHarmful(id, name)) harmful.Add(name);
}
_harmfulNow = harmful.Distinct(StringComparer.OrdinalIgnoreCase).ToArray();
_surgeActive = surge;
if (G.AutoDispel) TickDispel(nowMs, harmful.Count > 0);
if (G.SurgingStrength) TickSurge(nowMs, surge);
}
private void TickDispel(long now, bool anyHarmful)
{
// Verification / retry window after a rune use.
if (_verifyAt > 0)
{
if (now < _verifyAt) return;
if (!anyHarmful || _retries >= 3)
{
_dispelStatus = anyHarmful ? "debuffs remain after 3 retries" : "dispelled";
_verifyAt = 0;
_dispelCooldownUntil = now + Math.Max(2, G.DispelCooldownSeconds) * 1000L;
return;
}
_retries++;
if (UseRune(now)) _verifyAt = now + 2500;
return;
}
if (!anyHarmful) { _dispelStatus = "no harmful spells"; return; }
if (now < _dispelCooldownUntil) { _dispelStatus = "cooling down"; return; }
_retries = 0;
if (UseRune(now)) _verifyAt = now + 2000;
}
private bool UseRune(long now)
{
if (_ctx.Inventory.IsBusy) return false;
var rune = FindRune();
if (rune == null) { _dispelStatus = "no Rune of Dispel carried"; _dispelCooldownUntil = now + 30_000; _verifyAt = 0; return false; }
if (!_ctx.Inventory.Use(rune)) return false;
_dispelStatus = $"used {rune.Name} on {_harmfulNow.Length} debuff(s)";
return true;
}
private void TickSurge(long now, bool active)
{
if (active) { _surgeStatus = "Surging Strength active"; return; }
if (now < _surgeCooldownUntil || _ctx.Inventory.IsBusy) return;
var ember = FindEmber();
if (ember == null) { _surgeStatus = "no Empowered Volcanic Ember carried"; _surgeCooldownUntil = now + 30_000; return; }
if (_ctx.Inventory.Use(ember)) _surgeStatus = "used " + ember.Name;
_surgeCooldownUntil = now + Math.Max(5, G.SurgingCooldownSeconds) * 1000L;
}
public bool OnChat(string text)
{
if (!G.SurgingStrength) return false;
if (text.Contains("surging strength", StringComparison.OrdinalIgnoreCase))
{
if (text.Contains("you cast", StringComparison.OrdinalIgnoreCase) && text.Contains("on yourself", StringComparison.OrdinalIgnoreCase))
_surgeActive = true;
else if (text.Contains("has expired", StringComparison.OrdinalIgnoreCase))
{
_surgeActive = false;
_surgeCooldownUntil = 0; // re-apply on the next read
}
}
return false;
}
public void OnLogout()
{
_verifyAt = 0;
_harmfulNow = Array.Empty<string>();
}
// ── UI (render thread) ──────────────────────────────────────────────────
public void Render()
{
ImGui.TextColored(LegacyDashboardRenderer.ColTeal, "Auto-dispel (Rune of Dispel)");
bool ad = G.AutoDispel;
if (ImGui.Checkbox("Use a Rune of Dispel on harmful debuffs", ref ad)) G.AutoDispel = ad;
int cd = G.DispelCooldownSeconds;
ImGui.SetNextItemWidth(100);
if (ImGui.InputInt("Cooldown (s)##disp", ref cd)) G.DispelCooldownSeconds = Math.Max(2, cd);
ImGui.TextDisabled("Status: " + _dispelStatus);
var harm = _harmfulNow;
if (harm.Length > 0) ImGui.TextColored(LegacyDashboardRenderer.ColAmber, "Harmful now: " + string.Join(", ", harm));
if (ImGui.TreeNode("Always / never dispel lists"))
{
EditList("Always dispel (name contains)", G.DispelInclusions, ref _newInclude, "inc");
EditList("Never dispel (name contains)", G.DispelExclusions, ref _newExclude, "exc");
ImGui.TreePop();
}
ImGui.Separator();
ImGui.TextColored(LegacyDashboardRenderer.ColTeal, "Surging Strength");
bool ss = G.SurgingStrength;
if (ImGui.Checkbox("Keep Surging Strength up (Empowered Volcanic Ember)", ref ss)) G.SurgingStrength = ss;
ImGui.TextDisabled("Status: " + (_surgeActive ? "active" : _surgeStatus));
}
private void EditList(string label, List<string> list, ref string buffer, string id)
{
ImGui.TextUnformatted(label);
var snap = list.ToArray();
for (int i = 0; i < snap.Length; i++)
{
ImGui.BulletText(snap[i]);
ImGui.SameLine();
string victim = snap[i];
if (ImGui.SmallButton($"x##{id}{i}")) _ctx.Post(() => list.Remove(victim));
}
ImGui.SetNextItemWidth(200);
ImGui.InputTextWithHint($"##new{id}", "spell name text", ref buffer, 64u);
ImGui.SameLine();
if (ImGui.SmallButton($"Add##{id}") && buffer.Trim().Length > 0)
{
string add = buffer.Trim();
_ctx.Post(() => { if (!list.Contains(add, StringComparer.OrdinalIgnoreCase)) list.Add(add); });
buffer = string.Empty;
}
}
}

View file

@ -0,0 +1,141 @@
// IltCharmTracker.cs — Every ACECustom registry charm's state: the Mini Remote's Charms tab
// (IltCharms) and RynthPluginGetCharmsJson (an older engine's Settings "Charms Tracking" tab).
//
// Per charm it reports:
// acquired — "carried" (in pack / equipped now), "seen" (carried earlier this or a past
// session, remembered in IltCharacterState.CharmsSeen), or "no".
// active — "on" / "off" / "unknown". The charm's appraisal Use text ("Status: ON") wins;
// otherwise the player ability PropertyBool the server sets while it's active.
// The server deactivates abilities whose charm isn't possessed, so not carried = off.
// server — "off" when the server refused / reported the charm disabled, "on" when a feature
// dump reported it enabled, else "unknown" (clients can't query /charms).
// Pump thread only (inventory and property reads).
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace RynthCore.Plugin.RynthAi.IltHub;
internal sealed class IltCharmTracker
{
private readonly IltHubContext _ctx;
public IltCharmTracker(IltHubContext ctx) => _ctx = ctx;
/// <summary>
/// One charm's tracked state. <paramref name="ToggleId"/> is the carried copy a toggle uses
/// (the active one when one is on), 0 when none is carried.
/// </summary>
internal readonly record struct CharmState(
IltCharmDef Def, string Acquired, int Count, int Tier, int MaxTier,
IltTri Active, IltTri Server, DateTime LastSeenUtc, int ToggleId = 0);
/// <summary>Evaluates every registry charm and refreshes the "seen" memory for carried ones.</summary>
public List<CharmState> Evaluate()
{
var inv = _ctx.Inventory;
var seenMap = _ctx.State.Character.CharmsSeen;
var result = new List<CharmState>(IltInventory.Charms.Length);
// One inventory pass, grouped by charm definition, instead of a WCID scan per charm.
var carried = new Dictionary<IltCharmDef, List<WorldObject>>();
foreach (var wo in inv.Items())
{
var def = inv.CharmDefFor(wo);
if (def == null) continue;
if (!carried.TryGetValue(def, out var list)) carried[def] = list = new();
list.Add(wo);
}
foreach (var def in IltInventory.Charms)
{
carried.TryGetValue(def, out var items);
int count = items?.Count ?? 0;
int tier = 0, maxTier = 0, toggleId = 0;
IltTri active = IltTri.Off;
if (count > 0)
{
// Server allows only one active charm per ability, so any ON item means ON.
bool anyOn = false, allKnown = true;
toggleId = items![0].Id;
foreach (var wo in items!)
{
var (t, m) = inv.CharmTier(wo);
if (t > tier) { tier = t; maxTier = m; }
var st = inv.CharmStatus(wo);
if (st == IltTri.On) { anyOn = true; toggleId = wo.Id; }
else if (st == IltTri.Unknown) allKnown = false;
}
if (anyOn) active = IltTri.On;
else if (def.PlayerFlag != 0 && inv.PlayerBool(def.PlayerFlag)) active = IltTri.On;
else active = allKnown ? IltTri.Off : IltTri.Unknown;
if (!seenMap.TryGetValue(def.Name, out var seen)) seenMap[def.Name] = seen = new IltCharmSeen();
if (tier > seen.Tier) { seen.Tier = tier; seen.MaxTier = maxTier; }
// Day resolution keeps the persisted state from changing (and re-saving) every poll.
var today = DateTime.UtcNow.Date;
if (seen.LastSeenUtc != today) seen.LastSeenUtc = today;
}
seenMap.TryGetValue(def.Name, out var memory);
string acquired = count > 0 ? "carried" : memory != null ? "seen" : "no";
if (count == 0 && memory != null) { tier = memory.Tier; maxTier = memory.MaxTier; }
result.Add(new CharmState(def, acquired, count, tier, maxTier, active,
ServerState(def), memory?.LastSeenUtc ?? default, toggleId));
}
return result;
}
/// <summary>Server-side enabled state as far as the client has learned it.</summary>
private IltTri ServerState(IltCharmDef def)
{
var opts = _ctx.Options;
var tri = opts.Get(IltFeature.Charm(def.Name));
// Universal Summoning Mastery also has a ServerConfig switch, reported separately.
if (Array.IndexOf(def.Wcids, IltInventory.WcidUniversalMasteryCharm) >= 0)
{
var cfg = opts.Get(IltFeature.UniversalMastery);
if (cfg == IltTri.Off || tri == IltTri.Off) return IltTri.Off;
if (cfg == IltTri.On || tri == IltTri.On) return IltTri.On;
}
return tri;
}
/// <summary>JSON for RynthPluginGetCharmsJson. "available" is false off ILT-like worlds.</summary>
public string BuildJson()
{
var sb = new StringBuilder(4096);
bool available = _ctx.Options.IsIltLikeWorld;
sb.Append("{\"available\":").Append(available ? "true" : "false");
sb.Append(",\"world\":\"").Append(RynthAiPlugin.JsonEscape(_ctx.Options.WorldName ?? string.Empty)).Append('"');
if (!available) return sb.Append(",\"charms\":[]}").ToString();
var rows = Evaluate();
sb.Append(",\"total\":").Append(rows.Count);
sb.Append(",\"acquiredCount\":").Append(rows.Count(r => r.Acquired != "no"));
sb.Append(",\"activeCount\":").Append(rows.Count(r => r.Active == IltTri.On));
sb.Append(",\"charms\":[");
for (int i = 0; i < rows.Count; i++)
{
var r = rows[i];
if (i > 0) sb.Append(',');
sb.Append("{\"name\":\"").Append(RynthAiPlugin.JsonEscape(r.Def.Name)).Append('"');
sb.Append(",\"effect\":\"").Append(RynthAiPlugin.JsonEscape(r.Def.Effect)).Append('"');
sb.Append(",\"acquired\":\"").Append(r.Acquired).Append('"');
sb.Append(",\"count\":").Append(r.Count);
sb.Append(",\"tier\":").Append(r.Tier);
sb.Append(",\"maxTier\":").Append(r.MaxTier);
sb.Append(",\"active\":\"").Append(TriText(r.Active)).Append('"');
sb.Append(",\"server\":\"").Append(TriText(r.Server)).Append('"');
sb.Append(",\"lastSeen\":\"")
.Append(r.LastSeenUtc == default ? string.Empty : r.LastSeenUtc.ToString("yyyy-MM-dd"))
.Append("\"}");
}
sb.Append("]}");
return sb.ToString();
}
private static string TriText(IltTri t) => t switch { IltTri.On => "on", IltTri.Off => "off", _ => "unknown" };
}

View file

@ -0,0 +1,217 @@
// IltCharms.cs — The Mini Remote's "Charms" ILT tab: every ACECustom registry charm in one table.
//
// Per charm (IltCharmTracker): acquired ("carried" now, "stored" = carried before and remembered
// per character, or no), status ON / OFF from the charm's appraisal or the player's ability flag,
// best tier, and the server's switch when the client has learned it. A carried charm has a
// Toggle (using a charm flips it). The Guardian Hand isn't a registry charm (no published WCID),
// so it is matched by name or a configured WCID and listed under the table with its own Toggle.
// This was the engine Settings panel's "Charms Tracking" tab plus the Gear tab's charm strip.
// Scans run on the pump thread every 3 s while the Mini Remote is on screen; Render reads the
// published arrays only.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
using ImGuiNET;
using RynthCore.Plugin.RynthAi.LegacyUi;
namespace RynthCore.Plugin.RynthAi.IltHub;
internal sealed class IltCharms : IIltFeature
{
private const long ScanIntervalMs = 3000;
private readonly IltHubContext _ctx;
private readonly IltCharmTracker _tracker;
/// <summary>A Guardian Hand carried now (name or WCID match).</summary>
private sealed record HandRow(int Id, string Name, IltTri Status, bool ServerDisabled);
private volatile IltCharmTracker.CharmState[] _rows = Array.Empty<IltCharmTracker.CharmState>();
private volatile HandRow[] _hands = Array.Empty<HandRow>();
private long _lastScan;
public IltCharms(IltHubContext ctx, IltCharmTracker tracker)
{
_ctx = ctx;
_tracker = tracker;
}
private IltGearState G => _ctx.State.Gear;
private bool IsGuardianHand(WorldObject wo)
{
if (G.GuardianHandWcid != 0 && _ctx.Inventory.Wcid(wo) == G.GuardianHandWcid) return true;
string want = string.IsNullOrWhiteSpace(G.GuardianHandName) ? "Guardian Hand" : G.GuardianHandName.Trim();
return wo.Name.Contains(want, StringComparison.OrdinalIgnoreCase)
|| (wo.Name.Contains("guardian", StringComparison.OrdinalIgnoreCase) && wo.Name.Contains("hand", StringComparison.OrdinalIgnoreCase));
}
/// <summary>Pump thread: the registry table and the carried Guardian Hands.</summary>
private void Scan()
{
_rows = _tracker.Evaluate().ToArray();
var inv = _ctx.Inventory;
var hands = new List<HandRow>();
foreach (var wo in inv.Items().Where(IsGuardianHand))
hands.Add(new HandRow(wo.Id, wo.Name, inv.CharmStatus(wo), _ctx.Options.IsOff(IltFeature.Charm("Guardian Hand"))));
_hands = hands.ToArray();
}
/// <summary>Uses (toggles) a charm (pump thread).</summary>
private void Toggle(int id)
{
var wo = _ctx.Inventory.Cache?[id];
if (wo == null) return;
if (_ctx.Inventory.IsBusy) { _ctx.Chat("[Mini Remote] Busy - try the charm again in a moment."); return; }
_ctx.Inventory.Use(wo);
_lastScan = 0; // re-read the status soon (the appraisal refresh is throttled per item)
}
// ── IIltFeature ─────────────────────────────────────────────────────────
public void Tick(long nowMs)
{
if (!_ctx.WindowOpen || nowMs - _lastScan < ScanIntervalMs) return;
_lastScan = nowMs;
Scan();
}
public bool OnChat(string text) => false;
public void OnLogout()
{
_rows = Array.Empty<IltCharmTracker.CharmState>();
_hands = Array.Empty<HandRow>();
_lastScan = 0;
}
// ── UI (render thread) ──────────────────────────────────────────────────
public void Render()
{
var rows = _rows;
if (rows.Length == 0)
{
ImGui.TextDisabled(_ctx.WindowOpen ? "Reading your charms..." : "Open the Mini Remote to read your charms.");
RenderGuardianHand();
return;
}
int acquired = rows.Count(r => r.Acquired != "no"), active = rows.Count(r => r.Active == IltTri.On);
ImGui.TextColored(LegacyDashboardRenderer.ColTeal, $"{acquired} of {rows.Length} acquired, {active} active");
ImGui.SameLine();
if (ImGui.SmallButton("Refresh##charms")) _ctx.Post(() => { _lastScan = 0; });
const ImGuiTableFlags flags = ImGuiTableFlags.RowBg | ImGuiTableFlags.BordersInnerH | ImGuiTableFlags.SizingFixedFit
| ImGuiTableFlags.ScrollY;
float h = Math.Max(140f, ImGui.GetContentRegionAvail().Y - 110f);
if (ImGui.BeginTable("##iltcharms", 6, flags, new Vector2(0, h)))
{
ImGui.TableSetupScrollFreeze(0, 1);
ImGui.TableSetupColumn("Charm", ImGuiTableColumnFlags.WidthStretch);
ImGui.TableSetupColumn("Acquired", ImGuiTableColumnFlags.WidthFixed, 64);
ImGui.TableSetupColumn("Status", ImGuiTableColumnFlags.WidthFixed, 44);
ImGui.TableSetupColumn("Tier", ImGuiTableColumnFlags.WidthFixed, 40);
ImGui.TableSetupColumn("Server", ImGuiTableColumnFlags.WidthFixed, 58);
ImGui.TableSetupColumn("##toggle", ImGuiTableColumnFlags.WidthFixed, 52);
ImGui.TableHeadersRow();
for (int i = 0; i < rows.Length; i++) RenderRow(i, rows[i]);
ImGui.EndTable();
}
RenderGuardianHand();
ImGui.TextDisabled("Status comes from the charm's appraisal or your ability flag; a charm not carried is inactive.");
ImGui.TextDisabled("Stored = carried by this character before (remembered per character).");
}
private void RenderRow(int i, IltCharmTracker.CharmState r)
{
ImGui.PushID(i);
ImGui.TableNextRow();
ImGui.TableNextColumn();
bool carried = r.Acquired == "carried";
if (carried) ImGui.TextUnformatted(r.Def.Name);
else ImGui.TextColored(LegacyDashboardRenderer.ColTextMute, r.Def.Name);
if (ImGui.IsItemHovered() && r.Def.Effect.Length > 0) ImGui.SetTooltip(r.Def.Effect);
ImGui.TableNextColumn();
if (carried) ImGui.TextColored(LegacyDashboardRenderer.ColGreen, r.Count > 1 ? $"Carried x{r.Count}" : "Carried");
else if (r.Acquired == "seen")
{
ImGui.TextColored(LegacyDashboardRenderer.ColAmber, "Stored");
if (ImGui.IsItemHovered() && r.LastSeenUtc != default)
ImGui.SetTooltip("Last carried " + r.LastSeenUtc.ToString("yyyy-MM-dd"));
}
else ImGui.TextDisabled("No");
ImGui.TableNextColumn();
if (!carried) ImGui.TextDisabled("-");
else if (r.Active == IltTri.On) ImGui.TextColored(LegacyDashboardRenderer.ColGreen, "ON");
else if (r.Active == IltTri.Off) ImGui.TextColored(LegacyDashboardRenderer.ColTextMute, "OFF");
else
{
ImGui.TextColored(LegacyDashboardRenderer.ColAmber, "?");
if (ImGui.IsItemHovered()) ImGui.SetTooltip("Waiting for the charm's appraisal.");
}
ImGui.TableNextColumn();
ImGui.TextUnformatted(r.Tier <= 0 ? "-" : r.MaxTier > 0 ? $"{r.Tier}/{r.MaxTier}" : r.Tier.ToString());
ImGui.TableNextColumn();
if (r.Server == IltTri.Off)
{
ImGui.TextColored(LegacyDashboardRenderer.ColHp, "Disabled");
if (ImGui.IsItemHovered()) ImGui.SetTooltip("The server refused or reported this charm as disabled.");
}
else if (r.Server == IltTri.On) ImGui.TextColored(LegacyDashboardRenderer.ColGreen, "Enabled");
else
{
ImGui.TextDisabled("-");
if (ImGui.IsItemHovered()) ImGui.SetTooltip("Not reported. The server only tells players when a charm is refused.");
}
ImGui.TableNextColumn();
if (carried && r.ToggleId != 0 && r.Server != IltTri.Off)
{
int id = r.ToggleId;
if (ImGui.SmallButton("Toggle")) _ctx.Post(() => Toggle(id));
}
ImGui.PopID();
}
/// <summary>The Guardian Hand (not a registry charm): each carried one with a Toggle, and how it is matched.</summary>
private void RenderGuardianHand()
{
var hands = _hands;
foreach (var h in hands)
{
ImGui.PushID(h.Id);
if (h.ServerDisabled) ImGui.TextDisabled($"{h.Name} - disabled on this server");
else
{
var col = h.Status == IltTri.On ? LegacyDashboardRenderer.ColGreen
: h.Status == IltTri.Off ? LegacyDashboardRenderer.ColTextMute : LegacyDashboardRenderer.ColAmber;
ImGui.TextColored(col, h.Status == IltTri.On ? "ON " : h.Status == IltTri.Off ? "OFF" : " ? ");
ImGui.SameLine();
ImGui.TextUnformatted(h.Name);
ImGui.SameLine();
int id = h.Id;
if (ImGui.SmallButton("Toggle")) _ctx.Post(() => Toggle(id));
}
ImGui.PopID();
}
if (ImGui.TreeNode("Guardian Hand matching"))
{
string name = G.GuardianHandName;
ImGui.SetNextItemWidth(200);
if (ImGui.InputText("Name contains", ref name, 64u)) G.GuardianHandName = name;
int wcid = unchecked((int)G.GuardianHandWcid);
ImGui.SetNextItemWidth(140);
if (ImGui.InputInt("WCID (0 = name only)", ref wcid, 0)) G.GuardianHandWcid = unchecked((uint)Math.Max(0, wcid));
ImGui.TreePop();
}
}
}

View file

@ -0,0 +1,199 @@
// IltChatCapture.cs — Shared "send a server command and collect its reply" helper.
//
// Every ILT Hub feature that talks to ACECustom (/bank, /aug, /qb, /pets, /xp, /pb,
// /ilt features, the login probe, ...) goes through this one queue so that:
// * only one capture is in flight at a time (replies can't be attributed to the wrong
// request),
// * reply lines can be eaten so a Hub refresh doesn't spam the chat window,
// * an "Unknown command: X" reply is recognised uniformly (feature not on this server).
// All methods must be called on the plugin pump thread (OnTick / OnChatWindowText).
using System;
using System.Collections.Generic;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthAi.IltHub;
/// <summary>Describes one command whose reply should be captured.</summary>
internal sealed class IltChatRequest
{
/// <summary>Text handed to InvokeChatParser, e.g. "/bank".</summary>
public string Command = string.Empty;
/// <summary>True for lines that belong to this reply (captured, refresh the idle timer).</summary>
public Func<string, bool> IsResponseLine = _ => false;
/// <summary>Optional: a line that ends the reply immediately (it is captured too).</summary>
public Func<string, bool>? IsTerminator;
/// <summary>The reply is complete after this long with no new response line.</summary>
public int IdleEndMs = 2000;
/// <summary>Give up if no response line arrives within this long.</summary>
public int FirstLineTimeoutMs = 15000;
/// <summary>Hide captured lines from the chat window.</summary>
public bool Eat = true;
/// <summary>Invoked once on the pump thread when the capture finishes for any reason.</summary>
public Action<IltChatResult>? OnComplete;
}
/// <summary>What a capture produced.</summary>
internal sealed class IltChatResult
{
public readonly List<string> Lines = new();
/// <summary>No response line ever arrived.</summary>
public bool TimedOut;
/// <summary>The server answered "Unknown command: …" for this command.</summary>
public bool UnknownCommand;
/// <summary>The engine had no InvokeChatParser, so nothing was sent.</summary>
public bool NotSent;
public string? TerminatorLine;
}
internal sealed class IltChatCapture
{
private readonly RynthCoreHost _host;
private readonly Queue<IltChatRequest> _queue = new();
private IltChatRequest? _active;
private IltChatResult? _activeResult;
private long _sentAt;
private long _lastLineAt;
/// <summary>Minimum spacing between two sends so the server's own command throttles aren't tripped.</summary>
private const long SendSpacingMs = 400;
private long _lastSendAt;
private static long NowMs => Environment.TickCount64;
public IltChatCapture(RynthCoreHost host) => _host = host;
/// <summary>True while a capture is in flight or queued.</summary>
public bool IsBusy => _active != null || _queue.Count > 0;
/// <summary>True if a request with this exact command is queued or in flight (avoids duplicate refreshes).</summary>
public bool IsPending(string command)
{
if (_active != null && string.Equals(_active.Command, command, StringComparison.OrdinalIgnoreCase))
return true;
foreach (var r in _queue)
if (string.Equals(r.Command, command, StringComparison.OrdinalIgnoreCase))
return true;
return false;
}
/// <summary>Queues a capture. It is sent from <see cref="Tick"/> once earlier captures finish.</summary>
public void Enqueue(IltChatRequest request)
{
_queue.Enqueue(request);
RynthLog.Trace(LogCat.IltChat, $"enqueue '{request.Command}' (queue={_queue.Count}, busy={_active != null})");
}
/// <summary>Drops everything (logout / teardown). Pending callbacks are not invoked.</summary>
public void Clear()
{
if (_active != null || _queue.Count > 0)
RynthLog.Trace(LogCat.IltChat, $"clear: dropping active='{_active?.Command}' and {_queue.Count} queued");
_queue.Clear();
_active = null;
_activeResult = null;
}
/// <summary>Starts queued captures and finishes the active one on idle/timeout.</summary>
public void Tick()
{
long now = NowMs;
if (_active != null && _activeResult != null)
{
bool gotAny = _activeResult.Lines.Count > 0;
if (gotAny && now - _lastLineAt >= _active.IdleEndMs)
Finish();
else if (!gotAny && now - _sentAt >= _active.FirstLineTimeoutMs)
{
_activeResult.TimedOut = true;
Finish();
}
}
if (_active == null && _queue.Count > 0 && now - _lastSendAt >= SendSpacingMs)
StartNext(now);
}
/// <summary>
/// Feed every incoming chat line. Returns true when the line belonged to the active
/// capture and that capture asked for its lines to be eaten.
/// </summary>
public bool OnChatLine(string rawText)
{
if (_active == null || _activeResult == null) return false;
string text = rawText.Trim();
if (text.Length == 0) return false;
// "Unknown command: blackjack" — ACE GameActionTalk reply for unregistered commands.
if (text.StartsWith("Unknown command:", StringComparison.OrdinalIgnoreCase)
&& CommandWordMatches(text.Substring("Unknown command:".Length).Trim()))
{
_activeResult.UnknownCommand = true;
_activeResult.Lines.Add(text);
bool eat = _active.Eat;
Finish();
return eat;
}
if (_active.IsTerminator != null && _active.IsTerminator(text))
{
_activeResult.TerminatorLine = text;
_activeResult.Lines.Add(text);
bool eat = _active.Eat;
Finish();
return eat;
}
if (!_active.IsResponseLine(text)) return false;
_activeResult.Lines.Add(text);
_lastLineAt = NowMs;
RynthLog.Trace(LogCat.IltChat, $"line '{_active.Command}'{(_active.Eat ? " [eaten]" : "")}: {text}");
return _active.Eat;
}
private bool CommandWordMatches(string word)
{
if (_active == null) return false;
// Request "/bank t p 5 Bob" → command word "bank".
string cmd = _active.Command.TrimStart('/', '@');
int sp = cmd.IndexOf(' ');
if (sp >= 0) cmd = cmd.Substring(0, sp);
return string.Equals(cmd, word, StringComparison.OrdinalIgnoreCase);
}
private void StartNext(long now)
{
var req = _queue.Dequeue();
var result = new IltChatResult();
if (!_host.HasInvokeChatParser)
{
RynthLog.Trace(LogCat.IltChat, $"not sent '{req.Command}': engine has no InvokeChatParser");
result.NotSent = true;
try { req.OnComplete?.Invoke(result); }
catch (Exception ex) { RynthLog.Exception(LogCat.IltChat, ex, $"capture callback '{req.Command}'"); }
return;
}
_active = req;
_activeResult = result;
_sentAt = now;
_lastLineAt = now;
_lastSendAt = now;
RynthLog.Trace(LogCat.IltChat, $"send '{req.Command}' (idle={req.IdleEndMs} ms, timeout={req.FirstLineTimeoutMs} ms, eat={req.Eat})");
_host.InvokeChatParser(req.Command);
}
private void Finish()
{
var req = _active;
var res = _activeResult;
_active = null;
_activeResult = null;
if (req == null || res == null) return;
RynthLog.Trace(LogCat.IltChat,
$"complete '{req.Command}' in {NowMs - _sentAt} ms: lines={res.Lines.Count} timedOut={res.TimedOut} " +
$"unknown={res.UnknownCommand} terminator={(res.TerminatorLine != null)}");
try { req.OnComplete?.Invoke(res); }
catch (Exception ex) { RynthLog.Exception(LogCat.IltChat, ex, $"capture callback '{req.Command}'"); }
}
}

View file

@ -0,0 +1,282 @@
// IltChunkClap.cs — Lugian-hammer chunking and /clap automation (Gear tab).
//
// Chunk: uses a Lugian (Aetheria) Hammer on eligible items, one at a time:
// Aetheria — "Aetheria"/"Coalesced Aetheria" gems, not equipped, appraised, not flagged
// never-chunk (bool 9030), never levelled (ItemTotalXp quad 4 == 0), and
// max level (int 319) under the configured cap (Coalesced always qualifies).
// Corrupted — "Corrupted" melee/missile weapons with no tinks (171), no imbue (179),
// not equipped, not never-chunk, cleave (292) <= 1.
// Peace mode only unless ChunkInCombat; waits for the result line (10 s max).
// Clap: "/clap all" converts aetheria chunks + trinkets into coins server-side. Needs the
// AutoCraftingEnabled stamp; 30 min ± 2 min interval, first attempt ~1 min after enable.
using System;
using System.Collections.Generic;
using System.Linq;
using ImGuiNET;
using RynthCore.Loot;
using RynthCore.Plugin.RynthAi.LegacyUi;
namespace RynthCore.Plugin.RynthAi.IltHub;
internal sealed class IltChunkClap : IIltFeature
{
private const long ChunkResultWaitMs = 10_000;
private const long ClapFirstDelayMs = 60_000;
private const long ClapJitterMs = 120_000;
private static readonly string[] ChunkDoneLines =
{
"You smash the aetheria with the hammer.", "The two artifacts link together effortlessly.",
"You successfully chunk the aetheria.", "You fail to chunk the aetheria.",
"The corrupted weapon is crushed into a fine powder.", "You smash the corrupted weapon with the hammer.",
"The corrupted weapon shatters into fragments.", "You fail to chunk the corrupted weapon.",
};
private static readonly string[] ChunkRefusedLines =
{
"The aetheria is too powerful to chunk.", "You cannot chunk this aetheria.",
"The corrupted weapon is too powerful to chunk.", "You cannot chunk this corrupted weapon.",
};
private readonly IltHubContext _ctx;
private readonly Random _rng = new();
// Chunk state
private long _lastChunkAt;
private int _waitingOn;
private long _waitStartedAt;
private readonly HashSet<int> _skip = new();
private bool _manualPass;
private volatile string _chunkStatus = "idle";
private int _chunked;
// Clap state
private long _nextClapAt;
private volatile string _clapStatus = "idle";
private bool _clapWasEnabled;
public IltChunkClap(IltHubContext ctx) => _ctx = ctx;
private IltGearState G => _ctx.State.Gear;
// ── Chunk ───────────────────────────────────────────────────────────────
private WorldObject? FindHammer()
=> _ctx.Inventory.FindByName(n => n.Equals("Lugian Aetheria Hammer", StringComparison.OrdinalIgnoreCase)
|| n.Equals("Lugian Hammer", StringComparison.OrdinalIgnoreCase)
|| n.EndsWith(" Lugian Hammer", StringComparison.OrdinalIgnoreCase));
/// <summary>True/false when decidable; null when appraisal is still needed.</summary>
private bool? IsChunkableAetheria(WorldObject wo)
{
if (wo.ObjectClass != AcObjectClass.Gem) return false;
bool coalesced = wo.Name.Equals("Coalesced Aetheria", StringComparison.OrdinalIgnoreCase);
if (!coalesced && (!wo.Name.Contains("Aetheria", StringComparison.OrdinalIgnoreCase) || wo.Name.Contains("Chunk", StringComparison.OrdinalIgnoreCase)))
return false;
var inv = _ctx.Inventory;
if (inv.IsEquipped(wo)) return false;
if (!inv.HasAppraisal(wo)) { inv.RequestAppraisal(wo); return null; }
if (inv.Bool(wo, IltInventory.BoolNeverChunk)) return false;
if (inv.Quad(wo, IltInventory.QuadItemTotalXp) != 0) return false;
return coalesced || inv.Int(wo, IltInventory.IntItemMaxLevel) < Math.Max(1, G.ChunkAetheriaUnderLevel);
}
private bool? IsChunkableCorrupted(WorldObject wo)
{
if (wo.ObjectClass is not (AcObjectClass.MeleeWeapon or AcObjectClass.MissileWeapon)) return false;
if (!wo.Name.Contains("Corrupted", StringComparison.OrdinalIgnoreCase)) return false;
var inv = _ctx.Inventory;
if (inv.IsEquipped(wo)) return false;
if (!inv.HasAppraisal(wo)) { inv.RequestAppraisal(wo); return null; }
if (inv.Bool(wo, IltInventory.BoolNeverChunk)) return false;
if (inv.Int(wo, IltInventory.IntNumTimesTinkered) != 0 || inv.Int(wo, IltInventory.IntImbuedEffect) != 0) return false;
return inv.Int(wo, IltInventory.IntCleaving) <= 1;
}
private WorldObject? NextChunkTarget()
{
foreach (var wo in _ctx.Inventory.Items())
{
if (_skip.Contains(wo.Id)) continue;
if ((G.AutoChunkAetheria || _manualPass) && IsChunkableAetheria(wo) == true) return wo;
if ((G.AutoChunkCorrupted || _manualPass) && IsChunkableCorrupted(wo) == true) return wo;
}
return null;
}
/// <summary>Runs one chunk pass now (both item kinds) regardless of the auto toggles.</summary>
public void ChunkNow()
{
RynthLog.Trace(LogCat.IltGear, $"ChunkNow()");
_manualPass = true;
_lastChunkAt = 0;
_chunkStatus = "manual pass started";
}
private void TickChunk(long now)
{
if (!G.AutoChunkAetheria && !G.AutoChunkCorrupted && !_manualPass) return;
if (_waitingOn != 0)
{
if (now - _waitStartedAt < ChunkResultWaitMs) return;
_skip.Add(_waitingOn); // no result line — don't hammer the same item forever
_waitingOn = 0;
}
if (now - _lastChunkAt < Math.Max(500, G.ChunkIntervalMs)) return;
_lastChunkAt = now;
if (!G.ChunkInCombat && !_ctx.Inventory.InPeaceMode) { _chunkStatus = "waiting for peace mode"; return; }
if (_ctx.Inventory.IsBusy) return;
var hammer = FindHammer();
if (hammer == null) { _chunkStatus = "no Lugian Hammer carried"; _manualPass = false; return; }
var target = NextChunkTarget();
if (target == null)
{
_chunkStatus = _chunked > 0 ? $"nothing left to chunk ({_chunked} this session)" : "nothing eligible";
_manualPass = false;
return;
}
if (_ctx.Inventory.UseOn(hammer, unchecked((uint)target.Id)))
{
_waitingOn = target.Id;
_waitStartedAt = now;
_chunkStatus = "chunking " + target.Name;
}
}
// ── Clap ────────────────────────────────────────────────────────────────
private bool HasClapMaterials()
{
var inv = _ctx.Inventory;
foreach (var wo in inv.Items())
{
uint w = inv.Wcid(wo);
if ((w == IltInventory.WcidRedAetheriaChunk || w == IltInventory.WcidBlueAetheriaChunk)
&& inv.Int(wo, IltInventory.IntItemMaxLevel) <= 3)
return true;
string n = wo.Name;
if (n.Equals("Red Aetheria Chunk", StringComparison.OrdinalIgnoreCase) || n.Equals("Blue Aetheria Chunk", StringComparison.OrdinalIgnoreCase)
|| n.Equals("Ancient Empyrean Trinket", StringComparison.OrdinalIgnoreCase) || n.Equals("Ancient Falatacot Trinket", StringComparison.OrdinalIgnoreCase))
return true;
}
return false;
}
/// <summary>Sends "/clap all" through the capture queue (reply stays visible).</summary>
public void ClapNow(bool manual)
{
RynthLog.Trace(LogCat.IltGear, $"ClapNow(manual={manual})");
if (_ctx.Options.IsOff(IltFeature.Clap)) { _clapStatus = "/clap is not available (server or AutoCraftingEnabled stamp)"; return; }
if (_ctx.Capture.IsPending("/clap all")) return;
if (!manual && !HasClapMaterials()) { _clapStatus = "no aetheria materials carried"; return; }
_clapStatus = "sending /clap all...";
_ctx.Capture.Enqueue(new IltChatRequest
{
Command = "/clap all",
IsResponseLine = t => t.StartsWith("Deposited ", StringComparison.Ordinal)
|| t.StartsWith("[Clap]", StringComparison.OrdinalIgnoreCase)
|| t.Contains("aetheria materials", StringComparison.OrdinalIgnoreCase)
|| t.Contains("AutoCraftingEnabled", StringComparison.OrdinalIgnoreCase),
IdleEndMs = 800,
FirstLineTimeoutMs = 10_000,
Eat = false,
OnComplete = r =>
{
if (r.UnknownCommand) { _ctx.Options.Set(IltFeature.Clap, IltTri.Off); _clapStatus = "/clap not available"; return; }
_clapStatus = r.Lines.Count > 0 ? r.Lines[^1] : "no reply";
if (r.Lines.Any(l => l.StartsWith("Deposited ", StringComparison.Ordinal))) _ctx.Options.Set(IltFeature.Clap, IltTri.On);
},
});
}
private void TickClap(long now)
{
// Automation only runs once the server has positively confirmed /clap (unknown = wait).
if (!G.AutoClap || !_ctx.Options.IsOn(IltFeature.Clap)) { _clapWasEnabled = false; return; }
if (!_clapWasEnabled)
{
_clapWasEnabled = true;
_nextClapAt = now + ClapFirstDelayMs;
_clapStatus = "first auto-clap in ~1 min";
return;
}
if (now < _nextClapAt) return;
long interval = Math.Max(5, G.ClapIntervalMinutes) * 60_000L;
_nextClapAt = now + interval + (long)((_rng.NextDouble() * 2 - 1) * ClapJitterMs);
ClapNow(manual: false);
}
// ── IIltFeature ─────────────────────────────────────────────────────────
public void Tick(long nowMs)
{
TickChunk(nowMs);
TickClap(nowMs);
}
public bool OnChat(string text)
{
if (_waitingOn == 0) return false;
if (text.StartsWith("You're too busy", StringComparison.OrdinalIgnoreCase) || text.StartsWith("You are too busy", StringComparison.OrdinalIgnoreCase))
{
_waitingOn = 0; // retry the same item next interval
return false;
}
if (ChunkDoneLines.Any(l => text.Contains(l, StringComparison.OrdinalIgnoreCase)))
{
_chunked++;
_waitingOn = 0;
}
else if (ChunkRefusedLines.Any(l => text.Contains(l, StringComparison.OrdinalIgnoreCase)))
{
_skip.Add(_waitingOn);
_waitingOn = 0;
}
return false;
}
public void OnLogout()
{
_waitingOn = 0;
_skip.Clear();
_manualPass = false;
_clapWasEnabled = false;
}
// ── UI (render thread) ──────────────────────────────────────────────────
public void Render()
{
ImGui.TextColored(LegacyDashboardRenderer.ColTeal, "Chunking (Lugian Hammer)");
bool a = G.AutoChunkAetheria, c = G.AutoChunkCorrupted, comb = G.ChunkInCombat;
if (ImGui.Checkbox("Auto-chunk low aetheria", ref a)) G.AutoChunkAetheria = a;
ImGui.SameLine();
if (ImGui.Checkbox("Auto-chunk corrupted weapons", ref c)) G.AutoChunkCorrupted = c;
if (ImGui.Checkbox("Allow while in combat mode", ref comb)) G.ChunkInCombat = comb;
int under = G.ChunkAetheriaUnderLevel;
ImGui.SetNextItemWidth(100);
if (ImGui.InputInt("Chunk aetheria with max level below", ref under)) G.ChunkAetheriaUnderLevel = Math.Clamp(under, 1, 6);
if (ImGui.Button("Chunk eligible items now...")) _ctx.Confirm("Chunk items",
"Run one chunk pass now on every eligible aetheria and corrupted weapon?\nChunked items are destroyed.",
ChunkNow, "Chunk");
ImGui.TextDisabled("Status: " + _chunkStatus);
ImGui.Separator();
ImGui.TextColored(LegacyDashboardRenderer.ColTeal, "Clap (/clap all)");
if (_ctx.Options.IsOff(IltFeature.Clap))
{
ImGui.TextColored(LegacyDashboardRenderer.ColTextMute, "Not available (server off or AutoCraftingEnabled stamp missing).");
return;
}
bool ac = G.AutoClap;
if (ImGui.Checkbox("Auto-clap periodically", ref ac)) G.AutoClap = ac;
int mins = G.ClapIntervalMinutes;
ImGui.SetNextItemWidth(100);
if (ImGui.InputInt("Interval (min)", ref mins)) G.ClapIntervalMinutes = Math.Max(5, mins);
if (ImGui.SmallButton("Clap now")) _ctx.Post(() => ClapNow(manual: true));
ImGui.SameLine();
ImGui.TextDisabled(_clapStatus);
}
}

View file

@ -0,0 +1,264 @@
// IltEquipSuits.cs — UtilityBelt-style equipment profiles (.utl VTank loot files) (Gear tab, P2).
//
// A suit is a VTank loot profile: every carried wearable whose first matching rule is
// Keep belongs to the suit. Loading a suit:
// 1. dequip phase — equipped wearables NOT in the suit go to a pack with a free slot
// (WorldObjectCache.FindPackFor; never into a full pack — that crashes the client);
// 2. equip phase — suit items that aren't worn are used (AC equips on use).
// One action per 100 ms tick and only while not busy. An item is abandoned after 15
// attempts; the whole load bails after 10 s with no progress.
// Search order: RynthAi EquipProfiles\<char>, EquipProfiles, then UB's equip folders.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using ImGuiNET;
using RynthCore.Loot;
using RynthCore.Loot.VTank;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.Plugin.RynthAi.Loot;
using RynthCore.Install;
namespace RynthCore.Plugin.RynthAi.IltHub;
internal sealed class IltEquipSuits : IIltFeature
{
private const int MaxAttemptsPerItem = 15;
private const long NoProgressBailMs = 10_000;
private const long StepMs = 100;
private readonly IltHubContext _ctx;
// Load job (pump thread)
private readonly Queue<int> _dequip = new();
private readonly Queue<int> _equip = new();
private readonly Dictionary<int, int> _attempts = new();
private bool _running;
private long _lastStep, _lastProgress;
private int _doneCount;
private volatile string _status = "idle";
// Render snapshots
private volatile string[] _profiles = Array.Empty<string>();
private volatile string[] _preview = Array.Empty<string>();
private int _selected;
public IltEquipSuits(IltHubContext ctx) => _ctx = ctx;
private static readonly AcObjectClass[] WearableClasses =
{
AcObjectClass.Armor, AcObjectClass.Clothing, AcObjectClass.Gem, AcObjectClass.Jewelry,
AcObjectClass.MeleeWeapon, AcObjectClass.MissileWeapon, AcObjectClass.WandStaffOrb,
};
// ── Profile discovery ───────────────────────────────────────────────────
private IEnumerable<string> SearchDirs()
{
string root = Path.Combine(IltHubStore.SharedRoot, "EquipProfiles");
if (_ctx.CharName.Length > 0) yield return Path.Combine(root, _ctx.CharName);
yield return root;
string ub = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "Decal Plugins", "UtilityBelt");
string world = _ctx.Options.WorldName;
if (world.Length > 0 && _ctx.CharName.Length > 0) yield return Path.Combine(ub, world, _ctx.CharName, "equip");
if (world.Length > 0) yield return Path.Combine(ub, world, "equip");
yield return Path.Combine(ub, "equip");
}
/// <summary>All .utl profiles, first directory wins for duplicate names.</summary>
public List<(string Name, string Path)> ListProfiles()
{
var seen = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
foreach (string dir in SearchDirs())
{
try
{
if (!Directory.Exists(dir)) continue;
foreach (string f in Directory.GetFiles(dir, "*.utl"))
{
string n = Path.GetFileNameWithoutExtension(f);
if (!seen.ContainsKey(n)) seen[n] = f;
}
}
catch (Exception ex) { RynthLog.Exception(LogCat.IltGear, ex, $"equip dir {dir}"); }
}
return seen.OrderBy(k => k.Key, StringComparer.OrdinalIgnoreCase).Select(k => (k.Key, k.Value)).ToList();
}
private string? ResolveProfile(string? name)
{
if (string.IsNullOrWhiteSpace(name)) name = _ctx.CharName;
name = name!.Trim();
if (name.EndsWith(".utl", StringComparison.OrdinalIgnoreCase)) name = name[..^4];
return ListProfiles().FirstOrDefault(p => p.Name.Equals(name, StringComparison.OrdinalIgnoreCase)).Path;
}
/// <summary>Items the suit wants worn (first matching rule is Keep).</summary>
private List<WorldObject>? SuitItems(string path, out string error)
{
error = string.Empty;
VTankLootProfile profile;
try { profile = VTankLootParser.Load(path); }
catch (Exception ex) { error = "could not read profile: " + ex.Message; return null; }
var lootCtx = new VTankLootContext(_ctx.Host, _ctx.Inventory.PlayerId) { Cache = _ctx.Inventory.Cache };
var list = new List<WorldObject>();
foreach (var wo in _ctx.Inventory.Items())
{
if (Array.IndexOf(WearableClasses, wo.ObjectClass) < 0) continue;
if (_ctx.Inventory.Int(wo, IltInventory.IntValidLocations) == 0) continue;
VTankLootRule? match = null;
foreach (var rule in profile.Rules)
if (VTankLootEvaluator.Match(rule, wo, lootCtx)) { match = rule; break; }
if (match != null && match.Action == VTankLootAction.Keep) list.Add(wo);
}
return list;
}
// ── Commands (pump thread) ──────────────────────────────────────────────
public void RefreshProfileList() => _profiles = ListProfiles().Select(p => p.Name).ToArray();
/// <summary>Lists what a load would do without doing it. Returns lines (also shown in the UI).</summary>
public List<string> Test(string? name)
{
var lines = new List<string>();
string? path = ResolveProfile(name);
if (path == null) { lines.Add($"Profile not found: {name ?? _ctx.CharName}"); _preview = lines.ToArray(); return lines; }
var suit = SuitItems(path, out string err);
if (suit == null) { lines.Add(err); _preview = lines.ToArray(); return lines; }
var suitIds = suit.Select(s => s.Id).ToHashSet();
foreach (var wo in _ctx.Inventory.Items().Where(w => _ctx.Inventory.IsEquipped(w) && !suitIds.Contains(w.Id)
&& Array.IndexOf(WearableClasses, w.ObjectClass) >= 0))
lines.Add("dequip " + wo.Name);
foreach (var wo in suit.Where(w => !_ctx.Inventory.IsEquipped(w))) lines.Add("equip " + wo.Name);
if (lines.Count == 0) lines.Add("Already wearing this suit.");
_preview = lines.ToArray();
return lines;
}
/// <summary>Starts loading a suit.</summary>
public string Load(string? name)
{
RynthLog.Trace(LogCat.IltGear, $"Suits.Load(name='{name}')");
if (_running) return "A suit load is already running.";
if (!_ctx.Host.HasMoveItemInternal || !_ctx.Host.HasUseObject) return "Engine lacks MoveItemInternal/UseObject.";
string? path = ResolveProfile(name);
if (path == null) return $"Profile not found: {name ?? _ctx.CharName}";
var suit = SuitItems(path, out string err);
if (suit == null) return err;
var suitIds = suit.Select(s => s.Id).ToHashSet();
_dequip.Clear(); _equip.Clear(); _attempts.Clear();
foreach (var wo in _ctx.Inventory.Items().Where(w => _ctx.Inventory.IsEquipped(w) && !suitIds.Contains(w.Id)
&& Array.IndexOf(WearableClasses, w.ObjectClass) >= 0))
_dequip.Enqueue(wo.Id);
foreach (var wo in suit.Where(w => !_ctx.Inventory.IsEquipped(w))) _equip.Enqueue(wo.Id);
if (_dequip.Count + _equip.Count == 0) return "Already wearing this suit.";
_running = true;
_doneCount = 0;
_lastProgress = IltHubContext.NowMs;
_ctx.State.Gear.LastEquipProfile = Path.GetFileNameWithoutExtension(path);
_status = $"loading {Path.GetFileNameWithoutExtension(path)}: {_dequip.Count} off, {_equip.Count} on";
return _status;
}
public void Cancel(string why)
{
RynthLog.Trace(LogCat.IltGear, $"Suits.Cancel(why='{why}')");
_running = false;
_dequip.Clear();
_equip.Clear();
_status = why;
}
// ── IIltFeature ─────────────────────────────────────────────────────────
public void Tick(long nowMs)
{
if (!_running || nowMs - _lastStep < StepMs) return;
_lastStep = nowMs;
if (nowMs - _lastProgress > NoProgressBailMs) { Cancel($"no progress for 10 s - stopped ({_doneCount} done)"); return; }
if (_ctx.Inventory.IsBusy) return;
var cache = _ctx.Inventory.Cache;
if (cache == null) { Cancel("cache not ready"); return; }
// Dequip phase first so slots are free for the suit.
if (_dequip.Count > 0)
{
int id = _dequip.Peek();
var wo = cache[id];
if (wo == null || !_ctx.Inventory.IsEquipped(wo)) { _dequip.Dequeue(); Progress(nowMs); return; }
if (!Attempt(id)) { _dequip.Dequeue(); return; }
int pack = WorldObjectCache.FindPackFor(_ctx.Host, cache, includeMainPack: true, requireFree: 1);
if (pack == 0) { Cancel("no free pack slot for dequipped items - stopped"); return; }
_ctx.Host.MoveItemInternal(unchecked((uint)id), unchecked((uint)pack), 0, Math.Max(1, _ctx.Inventory.StackSize(wo)));
return;
}
if (_equip.Count > 0)
{
int id = _equip.Peek();
var wo = cache[id];
if (wo == null || _ctx.Inventory.IsEquipped(wo)) { _equip.Dequeue(); Progress(nowMs); return; }
if (!Attempt(id)) { _equip.Dequeue(); return; }
_ctx.Inventory.Use(wo);
return;
}
_running = false;
_status = $"suit loaded ({_doneCount} changes)";
}
/// <summary>Counts an attempt; false once the item has used up its attempts.</summary>
private bool Attempt(int id)
{
int n = _attempts.TryGetValue(id, out int a) ? a + 1 : 1;
_attempts[id] = n;
return n <= MaxAttemptsPerItem;
}
private void Progress(long now)
{
_doneCount++;
_lastProgress = now;
}
public bool OnChat(string text) => false;
public void OnLogout() => Cancel("idle");
// ── UI (render thread) ──────────────────────────────────────────────────
public void Render()
{
ImGui.TextColored(LegacyDashboardRenderer.ColTeal, "Equipment suits (.utl)");
if (ImGui.SmallButton("Rescan profiles")) _ctx.Post(RefreshProfileList);
var profiles = _profiles;
if (profiles.Length == 0)
{
ImGui.TextDisabled($"No .utl files found ({System.IO.Path.Combine(RynthInstallPaths.RynthAiDir, "EquipProfiles")} or UtilityBelt equip folders).");
}
else
{
_selected = Math.Clamp(_selected, 0, profiles.Length - 1);
ImGui.SetNextItemWidth(220);
ImGui.Combo("Suit", ref _selected, profiles, profiles.Length);
string pick = profiles[_selected];
ImGui.SameLine();
if (ImGui.SmallButton("Test")) _ctx.Post(() => Test(pick));
ImGui.SameLine();
if (ImGui.SmallButton("Load..."))
_ctx.Confirm("Load equipment suit", $"Swap to suit '{pick}'?\nItems not in the suit are moved to your packs.",
() => _ctx.Chat("[Mini Remote] " + Load(pick)), "Load");
if (_running)
{
ImGui.SameLine();
if (ImGui.SmallButton("Cancel")) _ctx.Post(() => Cancel("cancelled by player"));
}
}
ImGui.TextDisabled("Status: " + _status);
foreach (string l in _preview) ImGui.BulletText(l);
}
}

View file

@ -0,0 +1,254 @@
// IltGames.cs — ILT Hub "Games" tab + hand HUD (P2): Blackjack, Fellowship Blackjack, Powerball.
//
// Every bet / ticket purchase spends banked luminance, so each one needs a confirm.
// Blackjack is commented out on the current ACECustom build ("Unknown command:
// blackjack"); the pad only appears when the login probe found the command.
// /blackjack <bet>, /hit, /stand, /double, /split (fellowship: /fblackjack, /fhit, ...; max 100B)
// /pb (info), /pb buy <1-500>, /pb tickets
// The HUD is a small always-on-top window shown while a hand is in progress.
using System;
using System.Collections.Generic;
using System.Numerics;
using System.Text.RegularExpressions;
using ImGuiNET;
using RynthCore.Plugin.RynthAi.LegacyUi;
namespace RynthCore.Plugin.RynthAi.IltHub;
internal sealed class IltGames : IIltFeature
{
private const long FBlackjackMaxBet = 100_000_000_000;
private static readonly Regex Dealt = new(@"^You were dealt (?:a |an )?(?<card>.+?)\.$", RegexOptions.Compiled);
private static readonly Regex MyValue = new(@"Your (?:initial )?hand value is (?:now )?(?<v>\d+)", RegexOptions.Compiled);
private static readonly Regex DealerValue = new(@"Rand's (?:current )?hand value is (?<v>\d+)", RegexOptions.Compiled);
private readonly IltHubContext _ctx;
// Hand state (pump thread writes, render thread reads — simple fields / snapshot list)
private volatile bool _handActive;
private volatile bool _fellowshipHand;
private volatile string[] _cards = Array.Empty<string>();
private volatile int _myValue, _dealerValue;
private volatile string _lastResult = string.Empty;
// Powerball info
private volatile string _pbDraw = string.Empty, _pbJackpot = string.Empty, _pbPrice = string.Empty, _pbStatus = string.Empty;
// Render-thread input
private string _bjBetText = string.Empty, _fbjBetText = string.Empty;
public IltGames(IltHubContext ctx) => _ctx = ctx;
private IltGamesState S => _ctx.State.Games;
public bool AnyGameAvailable => _ctx.Options.IsOn(IltFeature.Blackjack) || _ctx.Options.IsOn(IltFeature.FBlackjack)
|| !_ctx.Options.IsOff(IltFeature.Powerball);
// ── Commands (pump thread) ──────────────────────────────────────────────
private void Send(string cmd)
{
if (_ctx.Host.HasInvokeChatParser) _ctx.Host.InvokeChatParser(cmd);
}
private void StartBlackjack(bool fellowship, long bet)
{
_fellowshipHand = fellowship;
_cards = Array.Empty<string>();
_myValue = _dealerValue = 0;
_lastResult = string.Empty;
Send($"/{(fellowship ? "fblackjack" : "blackjack")} {bet}");
}
private void HandAction(string verb) => Send("/" + (_fellowshipHand ? "f" : "") + verb);
public void RequestPowerballInfo()
{
RynthLog.Trace(LogCat.IltGames, $"RequestPowerballInfo()");
if (_ctx.Options.IsOff(IltFeature.Powerball) || _ctx.Capture.IsPending("/pb")) return;
_ctx.Capture.Enqueue(new IltChatRequest
{
Command = "/pb",
IsResponseLine = t => t.StartsWith("[Powerball]", StringComparison.OrdinalIgnoreCase)
|| t.StartsWith("Draw #", StringComparison.OrdinalIgnoreCase)
|| t.StartsWith("Jackpot Pool", StringComparison.OrdinalIgnoreCase)
|| t.StartsWith("Ticket Price", StringComparison.OrdinalIgnoreCase),
IdleEndMs = 1200,
FirstLineTimeoutMs = 8000,
Eat = true,
OnComplete = r =>
{
if (r.UnknownCommand) { _ctx.Options.Set(IltFeature.Powerball, IltTri.Off); return; }
if (r.Lines.Count > 0) _ctx.Options.Set(IltFeature.Powerball, IltTri.On);
foreach (string l in r.Lines) ParsePowerball(l);
RynthLog.Trace(LogCat.IltGames, $"/pb info: {r.Lines.Count} line(s), timedOut={r.TimedOut}");
_pbStatus = r.Lines.Count > 0 ? "updated " + DateTime.Now.ToString("t") : "no reply";
},
});
}
private void ParsePowerball(string l)
{
string t = l.Trim();
if (t.StartsWith("Draw #", StringComparison.OrdinalIgnoreCase)) _pbDraw = t;
else if (t.StartsWith("Jackpot Pool", StringComparison.OrdinalIgnoreCase)) _pbJackpot = t;
else if (t.StartsWith("Ticket Price", StringComparison.OrdinalIgnoreCase)) _pbPrice = t;
}
// ── IIltFeature ─────────────────────────────────────────────────────────
public void Tick(long nowMs) { }
public bool OnChat(string text)
{
// Powerball lines typed by the player still update the panel.
if (text.StartsWith("[Powerball]", StringComparison.OrdinalIgnoreCase))
{
if (text.Contains("You bought", StringComparison.OrdinalIgnoreCase) || text.Contains("Insufficient", StringComparison.OrdinalIgnoreCase))
_pbStatus = text;
return false;
}
string t = text.Trim();
if (t.StartsWith("Draw #", StringComparison.OrdinalIgnoreCase) || t.StartsWith("Jackpot Pool", StringComparison.OrdinalIgnoreCase)
|| t.StartsWith("Ticket Price", StringComparison.OrdinalIgnoreCase))
{
ParsePowerball(t);
return false;
}
// Blackjack
var d = Dealt.Match(text);
if (d.Success)
{
var list = new List<string>(_cards) { d.Groups["card"].Value };
_cards = list.ToArray();
_handActive = true;
return false;
}
var mv = MyValue.Match(text);
if (mv.Success) { _myValue = int.Parse(mv.Groups["v"].Value); _handActive = true; }
var dv = DealerValue.Match(text);
if (dv.Success) _dealerValue = int.Parse(dv.Groups["v"].Value);
if (text.StartsWith("The game begins!", StringComparison.OrdinalIgnoreCase)) _handActive = true;
if (text.StartsWith("Blackjack! You win", StringComparison.OrdinalIgnoreCase) || text.StartsWith("You won with", StringComparison.OrdinalIgnoreCase)
|| text.StartsWith("You tied with Rand", StringComparison.OrdinalIgnoreCase) || text.StartsWith("You lost with", StringComparison.OrdinalIgnoreCase)
|| text.StartsWith("You busted", StringComparison.OrdinalIgnoreCase))
_lastResult = text;
if (text.StartsWith("The blackjack game has ended", StringComparison.OrdinalIgnoreCase)
|| text.StartsWith("You are not currently in a blackjack game", StringComparison.OrdinalIgnoreCase))
_handActive = false;
if (text.StartsWith("You don't have enough luminance to place this bet", StringComparison.OrdinalIgnoreCase))
{
_lastResult = text;
_handActive = false;
}
return false;
}
public void OnLogout()
{
_handActive = false;
_cards = Array.Empty<string>();
}
// ── UI (render thread) ──────────────────────────────────────────────────
public void Render()
{
bool bj = _ctx.Options.IsOn(IltFeature.Blackjack), fbj = _ctx.Options.IsOn(IltFeature.FBlackjack);
if (!bj && !fbj && _ctx.Options.IsOff(IltFeature.Powerball))
{
ImGui.TextColored(LegacyDashboardRenderer.ColTextMute, "No games are enabled on this server.");
return;
}
bool hud = _ctx.State.GamesHudVisible;
if (ImGui.Checkbox("Show hand HUD while playing", ref hud)) _ctx.State.GamesHudVisible = hud;
if (bj && ImGui.CollapsingHeader("Blackjack", ImGuiTreeNodeFlags.DefaultOpen)) RenderBlackjack(false, ref _bjBetText);
if (fbj && ImGui.CollapsingHeader("Fellowship Blackjack", ImGuiTreeNodeFlags.DefaultOpen)) RenderBlackjack(true, ref _fbjBetText);
if (!bj && !fbj) ImGui.TextDisabled("Blackjack is not enabled on this server.");
if (!_ctx.Options.IsOff(IltFeature.Powerball) && ImGui.CollapsingHeader("Powerball", ImGuiTreeNodeFlags.DefaultOpen)) RenderPowerball();
}
private void RenderBlackjack(bool fellowship, ref string betText)
{
string id = fellowship ? "fbj" : "bj";
if (betText.Length == 0) betText = IltParse.Compact(fellowship ? S.FellowshipBlackjackBet : S.BlackjackBet).ToLowerInvariant();
ImGui.SetNextItemWidth(160);
ImGui.InputTextWithHint($"Bet (luminance)##{id}", "e.g. 1m, 500k", ref betText, 24u);
bool ok = IltParse.TryParseAmount(betText, out long bet) && (!fellowship || bet <= FBlackjackMaxBet);
ImGui.SameLine();
ImGui.TextDisabled(ok ? IltParse.N0(bet) : fellowship ? "invalid (max 100B)" : "invalid");
ImGui.BeginDisabled(!ok || _handActive);
if (ImGui.Button($"Deal...##{id}"))
{
long b = bet;
if (fellowship) S.FellowshipBlackjackBet = b; else S.BlackjackBet = b;
_ctx.Confirm(fellowship ? "Fellowship Blackjack" : "Blackjack",
$"Bet {IltParse.N0(b)} banked luminance on a new hand?", () => StartBlackjack(fellowship, b), "Bet");
}
ImGui.EndDisabled();
if (_handActive && _fellowshipHand == fellowship) RenderHandButtons(id);
if (_lastResult.Length > 0 && _fellowshipHand == fellowship) ImGui.TextWrapped(_lastResult);
}
private void RenderHandButtons(string id)
{
ImGui.TextUnformatted($"Hand: {string.Join(", ", _cards)} ({_myValue}) Rand: {(_dealerValue > 0 ? _dealerValue.ToString() : "?")}");
if (ImGui.Button($"Hit##{id}")) _ctx.Post(() => HandAction("hit"));
ImGui.SameLine();
if (ImGui.Button($"Stand##{id}")) _ctx.Post(() => HandAction("stand"));
ImGui.SameLine();
if (ImGui.Button($"Double...##{id}"))
_ctx.Confirm("Double down", "Double your bet on this hand?", () => HandAction("double"), "Double");
ImGui.SameLine();
if (ImGui.Button($"Split...##{id}"))
_ctx.Confirm("Split", "Split this hand (places a second bet)?", () => HandAction("split"), "Split");
}
private void RenderPowerball()
{
if (ImGui.SmallButton("Refresh##pb")) _ctx.Post(RequestPowerballInfo);
ImGui.SameLine();
if (ImGui.SmallButton("My tickets")) _ctx.Post(() => Send("/pb tickets"));
if (_pbDraw.Length > 0) ImGui.TextUnformatted(_pbDraw);
if (_pbJackpot.Length > 0) ImGui.TextUnformatted(_pbJackpot);
if (_pbPrice.Length > 0) ImGui.TextUnformatted(_pbPrice);
// Buying spends banked luminance, so it needs a positive server confirmation of /pb.
if (!_ctx.Options.IsOn(IltFeature.Powerball))
{
ImGui.TextDisabled("Ticket purchases unlock once the server confirms /pb (press Refresh).");
if (_pbStatus.Length > 0) ImGui.TextWrapped(_pbStatus);
return;
}
int qty = S.PowerballQuantity;
ImGui.SetNextItemWidth(120);
if (ImGui.InputInt("Tickets", ref qty)) S.PowerballQuantity = Math.Clamp(qty, 1, 500);
ImGui.SameLine();
if (ImGui.Button("Buy..."))
{
int q = S.PowerballQuantity;
_ctx.Confirm("Powerball", $"Buy {q} Powerball ticket(s)?\n{(_pbPrice.Length > 0 ? _pbPrice : "Tickets cost banked luminance.")}",
() => Send($"/pb buy {q}"), "Buy");
}
if (_pbStatus.Length > 0) ImGui.TextWrapped(_pbStatus);
}
/// <summary>Small HUD with the current hand; called every frame by the Hub UI.</summary>
public void RenderHud()
{
if (!_handActive || !_ctx.State.GamesHudVisible) return;
ImGui.SetNextWindowSize(new Vector2(300, 0), ImGuiCond.FirstUseEver);
bool open = true;
if (ImGui.Begin("Blackjack HUD##iltbjhud", ref open, ImGuiWindowFlags.AlwaysAutoResize | ImGuiWindowFlags.NoCollapse))
{
ImGui.TextColored(LegacyDashboardRenderer.ColAmber, _fellowshipHand ? "Fellowship Blackjack" : "Blackjack");
RenderHandButtons("hud");
}
ImGui.End();
if (!open) _ctx.State.GamesHudVisible = false;
}
}

View file

@ -0,0 +1,65 @@
// IltGear.cs — ILT Hub "Gear" tab: the gear tools.
//
// The sections are separate modules (buff keepers, chunk/clap, split arrows, equipment suits,
// VTank import) that this tab just lays out. The charm strip (registry charms and the Guardian
// Hand, with their toggles) is the Charms tab now (IltCharms).
using ImGuiNET;
namespace RynthCore.Plugin.RynthAi.IltHub;
internal sealed class IltGear : IIltFeature
{
public IltBuffKeepers Keepers { get; }
public IltChunkClap ChunkClap { get; }
public IltSplitArrows Split { get; }
public IltEquipSuits Suits { get; }
public IltUsdImporter Usd { get; }
public IltGear(IltHubContext ctx)
{
Keepers = new IltBuffKeepers(ctx);
ChunkClap = new IltChunkClap(ctx);
Split = new IltSplitArrows(ctx);
Suits = new IltEquipSuits(ctx);
Usd = new IltUsdImporter(ctx);
}
// ── IIltFeature ─────────────────────────────────────────────────────────
public void Tick(long nowMs)
{
Keepers.Tick(nowMs);
ChunkClap.Tick(nowMs);
Split.Tick(nowMs);
Suits.Tick(nowMs);
}
public bool OnChat(string text)
{
bool eat = Keepers.OnChat(text);
eat |= ChunkClap.OnChat(text);
eat |= Split.OnChat(text);
eat |= Suits.OnChat(text);
return eat;
}
public void OnLogout()
{
Keepers.OnLogout();
ChunkClap.OnLogout();
Split.OnLogout();
Suits.OnLogout();
}
// ── UI (render thread) ──────────────────────────────────────────────────
public void Render()
{
if (ImGui.CollapsingHeader("Dispel / Surging Strength", ImGuiTreeNodeFlags.DefaultOpen)) Keepers.Render();
if (ImGui.CollapsingHeader("Chunking / Clap")) ChunkClap.Render();
if (ImGui.CollapsingHeader("Split arrows")) Split.Render();
if (ImGui.CollapsingHeader("Equipment suits")) Suits.Render();
if (ImGui.CollapsingHeader("VirindiTank import")) Usd.Render();
ImGui.TextDisabled("Charms and the Guardian Hand are on the Charms tab.");
}
}

View file

@ -0,0 +1,571 @@
// IltGuardian.cs - Temple of Enlightenment guardians (ILT Hub "Guardian" window).
//
// * Riddle translator: incoming "Guardian of ... tells you / says" lines (when chat auto-detect
// is on) and pasted text go through IltGuardianPhrasebook; the answer shows here and on the
// Mini Remote.
// * Hand-in: gives one of the answer item to the guardian (GiveObjectTo). For the Temple
// guardian, when none is carried and "buy missing" is on, it first buys one from the open or
// nearest vendor (VendorBuy). Runs as a small pump-thread state machine with timeouts; the
// client busy state is respected between steps.
// * Attribute tracker: IltTempleAttributes.
//
// Threading: OnChat / Tick / commands run on the pump thread; Render only reads volatile fields
// and posts actions through IltHubContext.Post.
using System;
using System.Linq;
using System.Numerics;
using ImGuiNET;
using RynthCore.Loot;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.Plugin.RynthAi.Meta;
using RynthCore.Plugin.Shared;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthAi.IltHub;
internal sealed class IltGuardian : IIltFeature
{
/// <summary>The same guardian + answer from chat within this window is one prompt (tells repeat lines).</summary>
private const long DebounceMs = 2500;
private const long HandInTimeoutMs = 45_000;
private const long VendorOpenTimeoutMs = 10_000;
private const long BuyTimeoutMs = 10_000;
private const long ItemArriveTimeoutMs = 8_000;
private const long BusyRetryMs = 400;
private const int MaxGiveAttempts = 5;
/// <summary>How far (meters) to look for the guardian and a vendor.</summary>
private const double SearchRangeMeters = 60.0;
/// <summary>
/// PublicWeenieDesc BF_VENDOR. The world cache files vendors as creatures (Monster / Npc), never
/// AcObjectClass.Vendor, so vendors are recognised by this weenie flag.
/// </summary>
private const uint BfVendor = 0x200;
/// <summary>The Mini Remote shows the last answer for this long.</summary>
public static readonly TimeSpan AnswerShownFor = TimeSpan.FromMinutes(10);
private enum Step { Idle, FindItem, OpenVendor, WaitVendor, Buy, WaitBuy, WaitItem, Give }
private readonly IltHubContext _ctx;
private string _lastFingerprint = string.Empty;
private long _lastEmitAt;
// Last prompt (written on the pump thread, read by the render thread).
private volatile string _lastLine = string.Empty;
private volatile string _lastAnswer = string.Empty;
private volatile string _lastNpc = string.Empty;
private long _lastAnswerTicksUtc;
private volatile string _handInStatus = "idle";
// Hand-in state machine (pump thread only).
private Step _step = Step.Idle;
private string _item = string.Empty;
private string _npc = string.Empty;
private bool _asked;
private long _startedAt;
private long _stepDeadline;
private long _nextStepAt;
private uint _vendorId;
private uint _buyRequest;
private int _giveAttempts;
// Render-thread UI state.
private string _input = string.Empty;
public IltGuardian(IltHubContext ctx, Func<QuestTracker?> tracker, IltQuests quests)
{
_ctx = ctx;
Attributes = new IltTempleAttributes(ctx, tracker, quests);
}
public IltTempleAttributes Attributes { get; }
private IltGuardianState S => _ctx.State.Guardian;
/// <summary>Last answer item ("" until a guardian prompt was translated).</summary>
public string LastAnswer => _lastAnswer;
/// <summary>Guardian the last answer goes to.</summary>
public string LastNpc => _lastNpc;
/// <summary>The hand-in sequence is running.</summary>
public bool HandInRunning => _step != Step.Idle;
public string HandInStatus => _handInStatus;
/// <summary>Time since the last answer (MaxValue when there is none).</summary>
public TimeSpan LastAnswerAge
{
get
{
long t = System.Threading.Interlocked.Read(ref _lastAnswerTicksUtc);
return t == 0 ? TimeSpan.MaxValue : DateTime.UtcNow - new DateTime(t, DateTimeKind.Utc);
}
}
// ── IIltFeature ─────────────────────────────────────────────────────────
public void Tick(long nowMs)
{
Attributes.Tick(nowMs);
StepHandIn(nowMs);
}
public bool OnChat(string text)
{
if (!S.AutoDetectFromChat || !IltGuardianPhrasebook.LooksLikeIncomingGuardianLine(text)) return false;
_lastLine = text.Trim();
string answer = IltGuardianPhrasebook.Translate(text);
if (!IltGuardianPhrasebook.IsAnswer(answer)) return false;
string npc = IltGuardianPhrasebook.TurnInNpcFromLine(text);
long now = IltHubContext.NowMs;
string fingerprint = npc + "|" + answer;
if (fingerprint == _lastFingerprint && now - _lastEmitAt < DebounceMs) return false;
_lastFingerprint = fingerprint;
_lastEmitAt = now;
SetAnswer(answer, npc);
_ctx.Chat($"[ILT Guardian] {npc} wants: {answer}");
RynthLog.Write(LogCat.IltHub, $"[IltGuardian] chat answer '{answer}' for {npc}");
if (S.AutoHandIn) StartHandIn(answer, npc, asked: false);
return false; // never hide the guardian's own lines
}
public void OnLogout()
{
StopHandIn("stopped (logout)");
Attributes.OnLogout();
}
private void SetAnswer(string answer, string npc)
{
_lastAnswer = answer;
_lastNpc = npc;
System.Threading.Interlocked.Exchange(ref _lastAnswerTicksUtc, DateTime.UtcNow.Ticks);
}
/// <summary>Translates pasted text; a real answer becomes the current answer. Pump thread.</summary>
public string TranslateManual(string text)
{
string answer = IltGuardianPhrasebook.Translate(text);
if (!IltGuardianPhrasebook.IsAnswer(answer)) return answer;
string npc = IltGuardianPhrasebook.TurnInNpcFromInput(text);
_lastLine = text.Trim();
SetAnswer(answer, npc);
return $"{answer} (give to {npc})";
}
// ── Hand-in ─────────────────────────────────────────────────────────────
/// <summary>Starts giving <paramref name="item"/> to <paramref name="npc"/>. Pump thread.</summary>
public string StartHandIn(string item, string npc, bool asked)
{
if (!IltGuardianPhrasebook.IsAnswer(item)) return "No answer to hand in yet.";
if (!_ctx.Host.HasGiveObjectTo) return SetStatus("can't give items: update the RynthCore engine (API v62+).");
_item = item;
_npc = string.IsNullOrWhiteSpace(npc) ? IltGuardianPhrasebook.AttributeGuardian : npc;
_asked = asked;
_startedAt = IltHubContext.NowMs;
_nextStepAt = 0;
_vendorId = 0;
_buyRequest = 0;
_giveAttempts = 0;
_step = Step.FindItem;
RynthLog.Write(LogCat.IltHub, $"[IltGuardian] hand-in start: '{_item}' -> {_npc} ({(asked ? "asked" : "auto")})");
return SetStatus($"handing {_item} to {_npc}...");
}
/// <summary>Stops a running hand-in.</summary>
public void StopHandIn(string why = "stopped")
{
if (_step == Step.Idle) return;
_step = Step.Idle;
SetStatus(why);
RynthLog.Write(LogCat.IltHub, $"[IltGuardian] hand-in {why}");
}
private string SetStatus(string text)
{
_handInStatus = text;
return text;
}
private void Fail(string why)
{
_step = Step.Idle;
SetStatus("failed: " + why);
_ctx.Chat($"[ILT Guardian] Hand-in failed: {why}");
RynthLog.Write(LogCat.IltHub, $"[IltGuardian] hand-in failed: {why}");
}
private void Next(Step step, long nowMs, long timeoutMs = 0)
{
_step = step;
_stepDeadline = timeoutMs > 0 ? nowMs + timeoutMs : 0;
}
private void StepHandIn(long nowMs)
{
if (_step == Step.Idle || nowMs < _nextStepAt) return;
if (nowMs - _startedAt > HandInTimeoutMs) { Fail("timed out"); return; }
if (_stepDeadline != 0 && nowMs > _stepDeadline) { Fail(TimeoutText(_step)); return; }
var host = _ctx.Host;
switch (_step)
{
case Step.FindItem:
if (FindHandInItem() != null) { Next(Step.Give, nowMs); break; }
if (!IsTempleGuardian(_npc) || !S.BuyMissingFromVendor) { LogItemNearMisses(); Fail($"no {_item} in your packs"); break; }
Next(Step.OpenVendor, nowMs);
break;
case Step.OpenVendor:
{
if (!host.HasVendorTrade) { Fail($"no {_item} carried and vendor buying needs a newer RynthCore engine"); break; }
if (host.TryGetVendorInfo(out var open)) { _vendorId = open.VendorId; Next(Step.Buy, nowMs); break; }
var vendor = Nearest(IsVendor);
if (vendor == null) { LogVendorSearch(); Fail($"no {_item} carried and no vendor within {SearchRangeMeters:0} m"); break; }
RynthLog.Write(LogCat.IltHub, $"[IltGuardian] vendor for '{_item}': {vendor.Name} 0x{(uint)vendor.Id:X8}");
SetStatus($"opening {vendor.Name} to buy {_item}...");
host.UseFor(unchecked((uint)vendor.Id), "IltGuardian", $"buy {_item} for the Temple guardian",
_asked ? UseKind.Asked : UseKind.Auto);
Next(Step.WaitVendor, nowMs, VendorOpenTimeoutMs);
break;
}
case Step.WaitVendor:
if (host.TryGetVendorInfo(out var info) && info.ItemCount > 0) { _vendorId = info.VendorId; Next(Step.Buy, nowMs); }
break;
case Step.Buy:
{
if (!host.TryGetVendorInfo(out var v)) { Fail("the vendor closed"); break; }
if (v.TradeInFlight) { _nextStepAt = nowMs + BusyRetryMs; break; }
string want = NormalizeName(_item);
var match = host.GetVendorItems().FirstOrDefault(i => NormalizeName(i.Name) == want);
if (match == null) { Fail($"{v.Name} doesn't sell {_item}"); break; }
_buyRequest = host.VendorBuy(match.ObjectId, 1, v.VendorId);
if (_buyRequest == 0)
{
string why = host.TryGetVendorTradeStatus(out var st) && st.Message.Length > 0 ? st.Message : "refused";
Fail($"couldn't buy {_item}: {why}");
break;
}
SetStatus($"buying {_item} from {v.Name}...");
Next(Step.WaitBuy, nowMs, BuyTimeoutMs);
break;
}
case Step.WaitBuy:
if (!host.TryGetVendorTradeStatus(out var status) || status.RequestId != _buyRequest || !status.IsFinished) break;
if (!status.Succeeded) { Fail($"couldn't buy {_item}: {(status.Message.Length > 0 ? status.Message : status.Result.ToString())}"); break; }
Next(Step.WaitItem, nowMs, ItemArriveTimeoutMs);
break;
case Step.WaitItem:
if (FindHandInItem() != null) Next(Step.Give, nowMs);
break;
case Step.Give:
GiveStep(nowMs);
break;
}
}
private void GiveStep(long nowMs)
{
if (_ctx.Inventory.IsBusy)
{
SetStatus("waiting for the client (busy)...");
_nextStepAt = nowMs + BusyRetryMs;
return;
}
var item = FindHandInItem();
if (item == null) { LogItemNearMisses(); Fail($"no {_item} in your packs"); return; }
var npc = Nearest(wo => wo.Name.Contains(_npc, StringComparison.OrdinalIgnoreCase));
if (npc == null) { Fail($"{_npc} isn't nearby"); return; }
int stack = _ctx.Inventory.StackSize(item);
bool ok = _ctx.Host.GiveObjectTo(unchecked((uint)item.Id), unchecked((uint)npc.Id), stack > 1 ? 1 : 0);
RynthLog.Write(LogCat.IltHub, $"[IltGuardian] give '{item.Name}' 0x{(uint)item.Id:X8} (stack {stack}) -> {npc.Name} 0x{(uint)npc.Id:X8}: {ok}");
if (ok)
{
_step = Step.Idle;
SetStatus($"gave {item.Name} to {npc.Name}");
_ctx.Chat($"[ILT Guardian] Gave {item.Name} to {npc.Name}.");
return;
}
if (++_giveAttempts >= MaxGiveAttempts) { Fail("the give was refused"); return; }
_nextStepAt = nowMs + BusyRetryMs;
}
private static string TimeoutText(Step step) => step switch
{
Step.WaitVendor => "the vendor didn't open",
Step.WaitBuy => "the vendor didn't answer the purchase",
Step.WaitItem => "the bought item didn't arrive",
_ => "timed out",
};
private static bool IsTempleGuardian(string npc) =>
npc.Contains(IltGuardianPhrasebook.TempleGuardian, StringComparison.OrdinalIgnoreCase);
/// <summary>
/// A carried (not wielded) item named like the answer (case and spacing ignored). Reads AC's
/// live container contents: the cache's inventory set lags a purchase and also holds the open
/// vendor's stock, which can't be given.
/// </summary>
private WorldObject? FindHandInItem()
{
string want = NormalizeName(_item);
return CarriedItems().FirstOrDefault(wo => NormalizeName(wo.Name) == want && !_ctx.Inventory.IsEquipped(wo));
}
/// <summary>Live walk of the player's pack and side packs (falls back to the cache without the engine call).</summary>
private System.Collections.Generic.IReadOnlyList<WorldObject> CarriedItems()
=> _ctx.Inventory.Cache?.GetDirectInventory(forceRefresh: true) ?? Array.Empty<WorldObject>();
/// <summary>Lower-case, trimmed, single-spaced name for comparisons.</summary>
private static string NormalizeName(string name)
=> string.Join(' ', (name ?? string.Empty).Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries)).ToLowerInvariant();
/// <summary>Logs carried items sharing a word with the answer, so a name mismatch shows in the log.</summary>
private void LogItemNearMisses()
{
var items = CarriedItems();
var words = NormalizeName(_item).Split(' ').Where(w => w.Length > 3).ToArray();
var similar = items.Where(wo => words.Any(w => wo.Name.Contains(w, StringComparison.OrdinalIgnoreCase)))
.Take(8).Select(wo => $"'{wo.Name}' 0x{(uint)wo.Id:X8}").ToArray();
RynthLog.Write(LogCat.IltHub,
$"[IltGuardian] no '{_item}' among {items.Count} carried items; similar names: {(similar.Length > 0 ? string.Join(", ", similar) : "none")}");
}
/// <summary>A vendor (weenie BF_VENDOR flag, or a cache entry already classed Vendor).</summary>
private bool IsVendor(WorldObject wo)
{
if (wo.ObjectClass == AcObjectClass.Vendor) return true;
var host = _ctx.Host;
return host.HasGetObjectBitfield && host.TryGetObjectBitfield(unchecked((uint)wo.Id), out uint bf) && (bf & BfVendor) != 0;
}
/// <summary>Logs every vendor the cache sees with its distance (vendor search found none in range).</summary>
private void LogVendorSearch()
{
var cache = _ctx.Inventory.Cache;
int playerId = unchecked((int)_ctx.Inventory.PlayerId);
if (cache == null || playerId == 0) { RynthLog.Write(LogCat.IltHub, "[IltGuardian] vendor search: no world cache / player"); return; }
var landscape = cache.GetLandscapeObjects().ToList();
var vendors = landscape.Where(IsVendor).Take(8)
.Select(wo => $"'{wo.Name}' 0x{(uint)wo.Id:X8} {cache.Distance(playerId, wo.Id):0.0} m").ToArray();
RynthLog.Write(LogCat.IltHub,
$"[IltGuardian] vendor search: {landscape.Count} landscape objects, bitfield={(_ctx.Host.HasGetObjectBitfield ? "yes" : "no")}, "
+ $"vendors: {(vendors.Length > 0 ? string.Join(", ", vendors) : "none")}");
}
/// <summary>Nearest landscape object matching <paramref name="match"/> within SearchRangeMeters.</summary>
private WorldObject? Nearest(Func<WorldObject, bool> match)
{
var cache = _ctx.Inventory.Cache;
int playerId = unchecked((int)_ctx.Inventory.PlayerId);
if (cache == null || playerId == 0) return null;
WorldObject? best = null;
double bestDist = SearchRangeMeters;
foreach (var wo in cache.GetLandscapeObjects())
{
if (!match(wo)) continue;
double d = cache.Distance(playerId, wo.Id);
if (d <= bestDist) { bestDist = d; best = wo; }
}
return best;
}
// ── Commands ────────────────────────────────────────────────────────────
/// <summary>
/// "/ra guardian translate &lt;text&gt;|handin|stop|chat on|off|auto on|off|buy on|off|refresh|status".
/// "window" is handled by the controller. Pump thread.
/// </summary>
public void HandleCommand(string[] args)
{
string sub = args.Length > 0 ? args[0].ToLowerInvariant() : "status";
string rest = args.Length > 1 ? string.Join(" ", args.Skip(1)) : string.Empty;
switch (sub)
{
case "translate":
case "t":
_ctx.Chat("[ILT Guardian] " + TranslateManual(rest));
break;
case "handin":
case "give":
_ctx.Chat("[ILT Guardian] " + StartHandIn(_lastAnswer, _lastNpc, asked: true));
break;
case "stop":
StopHandIn();
_ctx.Chat("[ILT Guardian] Hand-in stopped.");
break;
case "chat":
S.AutoDetectFromChat = Toggle(rest, S.AutoDetectFromChat);
_ctx.Chat($"[ILT Guardian] Chat auto-detect {(S.AutoDetectFromChat ? "on" : "off")}.");
break;
case "auto":
S.AutoHandIn = Toggle(rest, S.AutoHandIn);
_ctx.Chat($"[ILT Guardian] Auto hand-in {(S.AutoHandIn ? "on" : "off")}.");
break;
case "buy":
S.BuyMissingFromVendor = Toggle(rest, S.BuyMissingFromVendor);
_ctx.Chat($"[ILT Guardian] Buy missing Temple items {(S.BuyMissingFromVendor ? "on" : "off")}.");
break;
case "refresh":
_ctx.Chat("[ILT Guardian] " + Attributes.Refresh());
break;
case "status":
_ctx.Chat($"[ILT Guardian] chat={(S.AutoDetectFromChat ? "on" : "off")} auto={(S.AutoHandIn ? "on" : "off")} buy={(S.BuyMissingFromVendor ? "on" : "off")} "
+ $"answer={(_lastAnswer.Length > 0 ? $"{_lastAnswer} -> {_lastNpc}" : "-")} hand-in: {_handInStatus}");
foreach (var r in Attributes.Snapshot)
_ctx.Chat($"[ILT Guardian] {r.Attribute,-12} {r.Npc,-16} #{r.Count} {r.Status} {r.Eta}");
break;
default:
_ctx.Chat("[ILT Guardian] /ra guardian [window [show|hide]|translate <text>|handin|stop|chat on|off|auto on|off|buy on|off|refresh|status]");
break;
}
}
private static bool Toggle(string mode, bool current) => mode.Trim().ToLowerInvariant() switch
{
"on" or "true" or "1" or "show" => true,
"off" or "false" or "0" or "hide" => false,
_ => !current,
};
// ── UI (render thread) ──────────────────────────────────────────────────
/// <summary>Guardian window body.</summary>
public void Render()
{
if (ImGui.CollapsingHeader("Riddle translator", ImGuiTreeNodeFlags.DefaultOpen)) RenderTranslator();
ImGui.Spacing();
if (ImGui.CollapsingHeader("Attribute turn-ins", ImGuiTreeNodeFlags.DefaultOpen)) RenderTracker();
}
private void RenderTranslator()
{
var s = S;
// Plain bool writes; the pump thread reads them on its next tick.
bool chat = s.AutoDetectFromChat;
if (ImGui.Checkbox("Detect from chat##grdchat", ref chat)) s.AutoDetectFromChat = chat;
if (ImGui.IsItemHovered()) ImGui.SetTooltip("Translate the guardians' tells as they arrive and show the answer here and on the Mini Remote.");
ImGui.SameLine();
bool auto = s.AutoHandIn;
if (ImGui.Checkbox("Auto hand-in##grdauto", ref auto)) s.AutoHandIn = auto;
if (ImGui.IsItemHovered()) ImGui.SetTooltip("After a chat answer, give one of the item to the guardian automatically.");
ImGui.SameLine();
bool buy = s.BuyMissingFromVendor;
if (ImGui.Checkbox("Buy if missing##grdbuy", ref buy)) s.BuyMissingFromVendor = buy;
if (ImGui.IsItemHovered()) ImGui.SetTooltip("Temple guardian: when you carry none, buy one from the open or nearest vendor first.");
string line = _lastLine;
if (line.Length > 0)
{
ImGui.TextDisabled("Heard:");
ImGui.SameLine();
ImGui.PushTextWrapPos(0f);
ImGui.TextDisabled(IltGuardianPhrasebook.MessageOf(line));
ImGui.PopTextWrapPos();
}
string answer = _lastAnswer, npc = _lastNpc;
if (answer.Length > 0)
{
ImGui.TextColored(LegacyDashboardRenderer.ColTeal, answer);
ImGui.SameLine();
ImGui.TextDisabled("-> " + npc);
if (HandInRunning)
{
if (ImGui.SmallButton("Stop##grdstop")) _ctx.Post(() => StopHandIn());
}
else if (ImGui.SmallButton("Hand in##grdgive"))
{
_ctx.Post(() => StartHandIn(answer, npc, asked: true));
}
}
else ImGui.TextDisabled("No guardian answer yet.");
ImGui.TextDisabled("Hand-in: " + _handInStatus);
ImGui.Spacing();
ImGui.InputTextMultiline("##grdinput", ref _input, 2048u, new Vector2(-1, 54));
if (ImGui.Button("Translate##grdtr"))
{
string text = _input;
_ctx.Post(() => _ctx.Chat("[ILT Guardian] " + TranslateManual(text)));
}
ImGui.SameLine();
if (ImGui.Button("Clear##grdclr")) _input = string.Empty;
ImGui.SameLine();
ImGui.TextDisabled("Paste a spell word or the riddle's question line.");
}
private void RenderTracker()
{
if (ImGui.SmallButton("Refresh##grdref")) _ctx.Post(() => _ctx.Chat("[ILT Guardian] " + Attributes.Refresh()));
if (ImGui.IsItemHovered()) ImGui.SetTooltip("Re-read /myquests and /qb list (the server allows each once a minute).");
ImGui.SameLine();
DateTime synced = Attributes.SyncedUtc;
ImGui.TextDisabled(synced == DateTime.MinValue ? "/qb not read this session" : $"/qb read {synced.ToLocalTime():t}");
ImGui.SameLine();
if (ImGui.SmallButton("Reset counts##grdreset"))
_ctx.Confirm("Reset turn-in counts", "Forget the turn-in counts and cooldown estimates taken from /qb wait stamps? (/myquests counts are not affected.)",
Attributes.ResetCounts, "Reset");
var rows = Attributes.Snapshot;
if (rows.Length > 0 && ImGui.BeginTable("##grdattr", 5, ImGuiTableFlags.RowBg | ImGuiTableFlags.BordersInnerH | ImGuiTableFlags.SizingStretchProp))
{
ImGui.TableSetupColumn("Attribute", ImGuiTableColumnFlags.None, 1.0f);
ImGui.TableSetupColumn("NPC", ImGuiTableColumnFlags.None, 1.3f);
ImGui.TableSetupColumn("#", ImGuiTableColumnFlags.None, 0.35f);
ImGui.TableSetupColumn("Status", ImGuiTableColumnFlags.None, 0.9f);
ImGui.TableSetupColumn("Next", ImGuiTableColumnFlags.None, 1.5f);
ImGui.TableHeadersRow();
foreach (var r in rows)
{
ImGui.TableNextRow();
ImGui.TableNextColumn(); ImGui.TextUnformatted(r.Attribute);
ImGui.TableNextColumn(); ImGui.TextUnformatted(r.Npc);
ImGui.TableNextColumn(); ImGui.TextUnformatted(r.Count.ToString());
ImGui.TableNextColumn();
var col = r.Ready ? LegacyDashboardRenderer.ColGreen
: r.Status == "Unknown" ? LegacyDashboardRenderer.ColTextMute
: LegacyDashboardRenderer.ColAmber;
ImGui.TextColored(col, r.Status);
if (ImGui.IsItemHovered())
ImGui.SetTooltip(r.FromMyQuests ? "From /myquests (exact)." : "From /qb wait stamps (count and timer are estimates).");
ImGui.TableNextColumn(); ImGui.TextUnformatted(r.Eta);
}
ImGui.EndTable();
}
int hours = S.CooldownHoursAssumed;
ImGui.SetNextItemWidth(140);
if (ImGui.SliderInt("Assumed cooldown (h)##grdhours", ref hours, 1, 72)) S.CooldownHoursAssumed = hours;
if (ImGui.IsItemHovered()) ImGui.SetTooltip("Used only for rows /myquests doesn't report: how long a /qb wait stamp lasts.");
}
/// <summary>
/// Mini Remote line: the last answer (for AnswerShownFor) with a Give / Stop button.
/// Draws nothing when there is no recent answer. Render thread.
/// </summary>
public void RenderRemoteLine()
{
string answer = _lastAnswer, npc = _lastNpc;
if (answer.Length == 0 || LastAnswerAge > AnswerShownFor) return;
ImGui.TextColored(LegacyDashboardRenderer.ColTextMute, "Guardian:");
ImGui.SameLine();
ImGui.TextColored(LegacyDashboardRenderer.ColTeal, answer);
if (ImGui.IsItemHovered()) ImGui.SetTooltip($"Give to {npc}\nHand-in: {_handInStatus}");
ImGui.SameLine();
if (HandInRunning)
{
if (ImGui.SmallButton("Stop##mrgrd")) _ctx.Post(() => StopHandIn());
}
else if (ImGui.SmallButton("Give##mrgrd"))
{
_ctx.Post(() => StartHandIn(answer, npc, asked: true));
}
}
}

View file

@ -0,0 +1,220 @@
// IltGuardianPhrasebook.cs - Temple of Enlightenment spell words and Guardian of Attribute
// Enlightenment riddles mapped to the item each guardian wants (Infinite Leaftide).
//
// Pure functions only (no host calls), so the Guardian window may translate on the render thread.
// The riddle table matches on the closing question line; lead-in lines alone return "No match".
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace RynthCore.Plugin.RynthAi.IltHub;
internal static class IltGuardianPhrasebook
{
public const string TempleGuardian = "Guardian of the Temple of Enlightenment";
public const string AttributeGuardian = "Guardian of Attribute Enlightenment";
/// <summary>Chat prefixes of an incoming guardian line ("tells you" or ACE's environmental "says").</summary>
private static readonly string[] IncomingPrefixes =
{
TempleGuardian + " tells you",
AttributeGuardian + " tells you",
TempleGuardian + " says",
AttributeGuardian + " says",
};
/// <summary>Help text returned when nothing was pasted.</summary>
public const string PasteHint = "Paste a spell word or riddle text, then Translate.";
/// <summary>Help text returned when the text didn't match any spell word or riddle.</summary>
public const string NoMatchHint = "No match: paste more lines from the guardian (especially the question line ending with ?).";
private static readonly Dictionary<string, string> TempleSpells = new(StringComparer.OrdinalIgnoreCase)
{
{ "Boquar", "Mugwort" }, { "Feazh", "Damiana" }, { "Kenrak", "Amaranth" },
{ "Puish", "Saffron" }, { "Shurov", "Comfrey" }, { "Volae", "Eyebright" },
{ "Cruath", "Ginseng" }, { "Helkas", "Wormwood" }, { "Malar", "Hyssop" },
{ "Quavosh", "Dragonsblood" }, { "Tugak", "Vervain" }, { "Yanoi", "Bistort" },
{ "Equin", "Mandrake" }, { "Jevak", "Myrrh" }, { "Ozhur", "Frankincense" },
{ "Roiga", "Yarrow" }, { "Uthoi", "Henbane" }, { "Zojak", "Hawthorn" },
};
/// <summary>Spell words longest first so a short word never shadows a longer one.</summary>
private static readonly KeyValuePair<string, string>[] TempleSpellsByLength =
TempleSpells.OrderByDescending(p => p.Key.Length).ToArray();
/// <summary>Normalized riddle phrases (longest first) and the item each answers.</summary>
private static readonly (string Needle, string Item)[] AttributeClues = BuildAttributeClues();
/// <summary>The same riddles split into meaningful words for the fuzzy fallback.</summary>
private static readonly (string Item, string[] Words)[] AttributeClueWords =
AttributeClues.Select(c => (c.Item, TokenizeMeaningfulWords(c.Needle))).ToArray();
private static (string, string)[] BuildAttributeClues()
{
var raw = new (string Phrase, string Item)[]
{
("what stone of shadow wields such arm", "Powdered Onyx"),
("what stone defends the mortal clay", "Powdered Agate"),
("what heavy stone keeps adventurers healed", "Powdered Hematite"),
("what heavy stone keeps adventure's healed", "Powdered Hematite"),
("what honeyed stone bids pain to leave", "Powdered Amber"),
("what draught unweaves that mages send", "Chorizite"),
("what gem of life beats deep within", "Powdered Bloodstone"),
("what ruddy gem calls vigor nigh", "Powdered Carnelian"),
("what lunar gem gives peace to mind", "Powdered Moonstone"),
("what verdant gem reveals the way", "Powdered Malachite"),
("what crystal tunes the life it soothes", "Powdered Quartz"),
("what gem of sky makes items nice", "Powdered Turquoise"),
("what vial holds my burning scar", "Brimstone"),
("which draught brings forth the fire's scent", "Turpeth"),
("race the wind yet leave no trace", "Cadmia"),
("grant the hand a dancer grace", "Cadmia"),
("no wings I bear yet fleet I flee", "Cadmia"),
("what draught awakens speed in thee", "Cadmia"),
("what deaught awakens speed in thee", "Cadmia"),
("what potion turns mana-use to one", "Cinnabar"),
("what azure draught makes thunder weep", "Cobalt"),
("what draught commands the winter's tide", "Colcothar"),
("what pale draught prevents acid's writhe", "Gypsum"),
("whate pale draught prevents acid's writhe", "Gypsum"),
("what liquid turns heart grey between", "Quicksilver"),
("what potion pierces the unseen end", "Realgar"),
("what shadowed draught makes swiftness lie", "Stibnite"),
("what verdant vial hides cuts unseen", "Verdigris"),
("what potion shakes both flesh and floor", "Vitriol"),
("what river wood trades life as art", "Alder Talisman"),
("what wood enchants both bane and skill", "Ashwood Talisman"),
("what pale wood casts the striker's bane", "Birch Talisman"),
("what sacred stem keeps harm outside", "Cedar Talisman"),
("what dark wood diminishes the foe's own tune", "Blackthorn Talisman"),
("what hardwood charm makes others stand", "Ebony Talisman"),
("what aged branch makes circles run", "Elder Talisman"),
("what mystic bough binds here to yore", "Hazel Talisman"),
("what poisoned branch brings creeping death", "Hemlock Talisman"),
("what steadfast wood makes volleys rained", "Oak Talisman"),
("what living wand makes allies mend", "Poplar Talisman"),
("what sacred wood the self amends", "Rowan Talisman"),
("what supple wood restores me here", "Willow Talisman"),
("what ancient bough lets lifeblood grow", "Yew Talisman"),
};
return raw.Select(t => (NormalizePhrase(t.Phrase), t.Item))
.OrderByDescending(t => t.Item1.Length)
.ToArray();
}
/// <summary>Lowercase, curly apostrophes folded, punctuation collapsed to single spaces.</summary>
private static string NormalizePhrase(string s)
{
if (string.IsNullOrWhiteSpace(s)) return string.Empty;
string lower = s.Trim().ToLowerInvariant().Replace('\u2019', '\'');
var sb = new StringBuilder(lower.Length);
bool pendingSpace = false;
foreach (char c in lower)
{
bool wordCh = (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '\'';
if (!wordCh) { pendingSpace = true; continue; }
if (pendingSpace && sb.Length > 0) { sb.Append(' '); pendingSpace = false; }
sb.Append(c);
}
return sb.ToString().Trim();
}
/// <summary>Words of 3+ letters minus question / filler words.</summary>
private static string[] TokenizeMeaningfulWords(string normalized) =>
normalized.Split(' ', StringSplitOptions.RemoveEmptyEntries)
.Where(w => w.Length >= 3 && w is not ("what" or "which" or "the" or "and" or "for"))
.ToArray();
/// <summary>
/// Typo-tolerant fallback: the riddle whose words overlap the input best, needing at least four
/// shared words and 72% of the riddle's words so a near-miss never maps to the wrong item.
/// </summary>
private static string? TryFuzzyAttributeMatch(string blob)
{
var inputWords = TokenizeMeaningfulWords(blob);
if (inputWords.Length == 0) return null;
var inputSet = new HashSet<string>(inputWords, StringComparer.Ordinal);
string? bestItem = null;
double bestScore = 0d;
foreach (var (item, words) in AttributeClueWords)
{
if (words.Length == 0) continue;
int matches = words.Count(inputSet.Contains);
double score = (double)matches / words.Length;
if (matches >= 4 && score >= 0.72d && score > bestScore)
{
bestScore = score;
bestItem = item;
}
}
return bestItem;
}
/// <summary>Resolves guardian text to an item name, or one of the help strings.</summary>
public static string Translate(string raw)
{
string blob = NormalizePhrase(raw);
if (blob.Length == 0) return PasteHint;
var tokens = Regex.Split(blob, @"[^a-z0-9']+").Where(t => t.Length > 0).ToList();
foreach (var pair in TempleSpellsByLength)
if (tokens.Any(t => t.Equals(pair.Key, StringComparison.OrdinalIgnoreCase)))
return pair.Value;
foreach (var pair in TempleSpellsByLength)
if (blob.Contains(pair.Key.ToLowerInvariant(), StringComparison.Ordinal))
return pair.Value;
foreach (var (needle, item) in AttributeClues)
if (needle.Length > 0 && blob.Contains(needle, StringComparison.Ordinal))
return item;
return TryFuzzyAttributeMatch(blob) ?? NoMatchHint;
}
/// <summary>False for the help strings Translate returns when nothing matched.</summary>
public static bool IsAnswer(string translation) =>
!string.IsNullOrWhiteSpace(translation) && translation != PasteHint && translation != NoMatchHint;
/// <summary>True when the line starts like an incoming guardian tell / say.</summary>
public static bool LooksLikeIncomingGuardianLine(string raw)
{
if (string.IsNullOrWhiteSpace(raw)) return false;
string t = raw.TrimStart();
foreach (string prefix in IncomingPrefixes)
if (t.StartsWith(prefix, StringComparison.OrdinalIgnoreCase))
return true;
return false;
}
/// <summary>The guardian to give the item to, read from an incoming line (Attribute when unclear).</summary>
public static string TurnInNpcFromLine(string raw)
{
if (!string.IsNullOrEmpty(raw) && raw.Contains(TempleGuardian, StringComparison.OrdinalIgnoreCase))
return TempleGuardian;
return AttributeGuardian;
}
/// <summary>
/// The guardian for manually pasted text: the name in a pasted chat line, else a Temple spell
/// word means the Temple guardian, else the Attribute guardian.
/// </summary>
public static string TurnInNpcFromInput(string raw)
{
if (string.IsNullOrWhiteSpace(raw)) return AttributeGuardian;
if (raw.Contains(TempleGuardian, StringComparison.OrdinalIgnoreCase)) return TempleGuardian;
if (raw.Contains(AttributeGuardian, StringComparison.OrdinalIgnoreCase)) return AttributeGuardian;
foreach (string word in TempleSpells.Keys)
if (raw.Contains(word, StringComparison.OrdinalIgnoreCase))
return TempleGuardian;
return AttributeGuardian;
}
/// <summary>The quoted message of a guardian line ("... tells you, \"text\"" → text); the line itself otherwise.</summary>
public static string MessageOf(string line)
{
int open = line.IndexOf('"');
int close = line.LastIndexOf('"');
return open >= 0 && close > open ? line.Substring(open + 1, close - open - 1).Trim() : line.Trim();
}
}

View file

@ -0,0 +1,111 @@
// IltHubContext.cs — Shared services handed to every ILT Hub feature.
//
// Threading contract:
// * Feature Tick / OnChat run on the plugin pump thread and may call the host freely.
// * Feature Render runs on the ImGui render thread and must NOT call AC actions directly.
// It calls Post(...) to run work on the next pump tick, or Confirm(...) to ask the
// player first (the confirmed action is then posted). This mirrors the existing
// DrainMetaCommands pattern in RynthAiPlugin.
using System;
using System.Collections.Concurrent;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthAi.IltHub;
/// <summary>A yes/no question waiting for the player (a modal over the Mini Remote).</summary>
internal sealed class IltConfirmRequest
{
public string Title = "Confirm";
public string Message = string.Empty;
public string YesLabel = "Yes";
/// <summary>Runs on the pump thread after the player clicks Yes.</summary>
public Action? OnYes;
}
internal sealed class IltHubContext
{
private readonly ConcurrentQueue<Action> _posted = new();
private readonly ConcurrentQueue<IltConfirmRequest> _confirms = new();
private readonly Func<LegacyUiSettings?> _settings;
public IltHubContext(RynthCoreHost host, IltHubState state, IltHubStore store, IltChatCapture capture,
IltServerOptions options, IltInventory inventory, Func<LegacyUiSettings?> settings)
{
Host = host;
State = state;
Store = store;
Capture = capture;
Options = options;
Inventory = inventory;
_settings = settings;
}
public RynthCoreHost Host { get; }
public IltHubState State { get; }
public IltHubStore Store { get; }
public IltChatCapture Capture { get; }
public IltServerOptions Options { get; }
public IltInventory Inventory { get; }
/// <summary>The live combat settings (rule lists the Pet picker / USD importer edit). Null before login.</summary>
public LegacyUiSettings? Settings => _settings();
/// <summary>Set by the controller when combat settings were edited and must be saved.</summary>
public Action? SaveCombatSettings;
/// <summary>Logged-in character name (resolved at login).</summary>
public string CharName = string.Empty;
/// <summary>True when the Mini Remote is on screen (features use it to gate auto-refreshes).</summary>
public bool WindowOpen => State.WindowVisible;
/// <summary>
/// Shows the Mini Remote on one of its ILT tabs (set by the controller). Any thread: it only
/// records the tab and the show request, which the next frame applies.
/// </summary>
public Action<IltSection>? ShowTab;
/// <summary>Writes a local chat line (never sent to the server).</summary>
public void Chat(string text)
{
if (Host.HasWriteToChat) Host.WriteToChat(text, 1);
}
/// <summary>Queues work for the next pump tick (safe from the render thread).</summary>
public void Post(Action action) => _posted.Enqueue(action);
/// <summary>Asks the player to confirm before <paramref name="onYes"/> runs on the pump thread.</summary>
public void Confirm(string title, string message, Action onYes, string yesLabel = "Yes")
=> _confirms.Enqueue(new IltConfirmRequest { Title = title, Message = message, OnYes = onYes, YesLabel = yesLabel });
/// <summary>Render thread: takes the next pending confirmation, if any.</summary>
public bool TryTakeConfirm(out IltConfirmRequest request) => _confirms.TryDequeue(out request!);
/// <summary>Pump thread: runs everything posted since the last tick.</summary>
public void DrainPosted()
{
int guard = 0;
while (guard++ < 64 && _posted.TryDequeue(out var a))
{
try { a(); }
catch (Exception ex) { RynthLog.Exception(LogCat.IltHub, ex, "posted action"); }
}
}
/// <summary>Elapsed-ms clock used for every Hub timer.</summary>
public static long NowMs => Environment.TickCount64;
}
/// <summary>Contract every Hub feature module implements.</summary>
internal interface IIltFeature
{
/// <summary>Pump-thread tick (~every plugin tick).</summary>
void Tick(long nowMs);
/// <summary>Pump-thread chat line. Return true to hide the line from the chat window.</summary>
bool OnChat(string text);
/// <summary>Logout / teardown: stop automation, drop transient state.</summary>
void OnLogout();
}

View file

@ -0,0 +1,612 @@
// IltHubController.cs — Owns the ILT features behind the Mini Remote: state, services, feature
// modules, commands.
//
// RynthAiPlugin creates one controller per login session and forwards:
// OnTick → Tick() (pump thread)
// OnChatWindowText → OnChat() (pump thread; returns true to eat the line)
// OnRender → Render() (render thread: Games HUD, quest favorites HUD, confirmations)
// /ra hub ..., /ra quests ..., /ra guardian ... → HandleCommand()
// OnLogout / teardown → OnLogout()
// The ILT sections are Mini Remote tabs (RenderTab); the Guardian is RynthCore's ILT panel
// (RenderGuardianPanel), and bounties are the RynthILT plugin's (RynthCore's ILT button), so
// "/ra bounty" and "/ra guardian window" open those engine panels.
// The Quests and Pets tabs (and their features) are universal: every world. The ILT tabs only
// appear on ACECustom/ILT worlds where at least one server feature is on; on every other world
// the ILT features stay dormant (no probes, no chat, no tabs).
using System;
using System.Collections.Generic;
using System.Linq;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.Plugin.RynthAi.Meta;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthAi.IltHub;
internal sealed class IltHubController
{
private const long SaveIntervalMs = 5000;
private readonly IltHubContext _ctx;
private readonly IltHubUi _ui;
private readonly Func<QuestTracker?> _quests;
private readonly List<IIltFeature> _features = new();
private long _lastSaveAt;
private bool _questOutcomeHooked;
private bool _availabilityAnnounced; // "/ra hub to open" hint printed this session
public IltBanking Banking { get; }
public IltPets Pets { get; }
public IltSessionRates Rates { get; }
public IltQuests Quests { get; }
public IltProgression Progression { get; }
public IltGear Gear { get; }
public IltGames Games { get; }
/// <summary>Registry charm acquired / active / server state (the Charms tab and RynthPluginGetCharmsJson).</summary>
public IltCharmTracker Charms { get; }
/// <summary>The Mini Remote's Charms tab (registry charms with toggles, the Guardian Hand).</summary>
public IltCharms CharmsTab { get; }
/// <summary>Temple guardians: riddle translator, hand-in, attribute turn-in tracker.</summary>
public IltGuardian Guardian { get; }
public IltHubController(RynthCoreHost host, string charFolder, Func<WorldObjectCache?> cache,
Func<LegacyUiSettings?> settings, Func<QuestTracker?> quests, Action saveCombatSettings,
RynthCore.Plugin.Shared.SessionStatsTracker? sessionStats = null)
{
var store = new IltHubStore(host, charFolder);
var state = store.LoadState();
var capture = new IltChatCapture(host);
var inventory = new IltInventory(host, cache);
IltHubContext? ctxRef = null;
var options = new IltServerOptions(host, capture, state, text => ctxRef?.Chat(text), settings);
// Settings > Misc shows whether the per-character Hub override is on too.
ServerFeatureGate.HubForceProvider = () => state.ForceLeaftideFeatures;
_ctx = new IltHubContext(host, state, store, capture, options, inventory, settings) { SaveCombatSettings = saveCombatSettings };
ctxRef = _ctx;
_quests = quests;
Banking = new IltBanking(_ctx);
Pets = new IltPets(_ctx);
Rates = new IltSessionRates(_ctx, sessionStats);
Quests = new IltQuests(_ctx, quests);
Progression = new IltProgression(_ctx);
Gear = new IltGear(_ctx);
Games = new IltGames(_ctx);
Charms = new IltCharmTracker(_ctx);
CharmsTab = new IltCharms(_ctx, Charms);
Guardian = new IltGuardian(_ctx, quests, Quests);
_features.AddRange(new IIltFeature[] { Banking, Pets, Rates, Quests, Progression, Gear, CharmsTab, Games, Guardian });
Banking.BalanceChanged += Rates.OnBankBalanceChanged;
Rates.MovingMoney = () => Banking.MovingMoney;
options.ProbeReplyTap = OnProbeReply;
_ui = new IltHubUi(this, _ctx);
_ctx.ShowTab = section => MiniRemoteTabCommand?.Invoke(IltSections.TabId(section), "show");
}
public IltHubState State => _ctx.State;
public IltServerOptions Options => _ctx.Options;
/// <summary>
/// Shows / hides / toggles the Mini Remote ("show", "hide", "toggle"). Set by RynthAiPlugin;
/// returns the chat reply. Pump thread.
/// </summary>
public Func<string, string>? MiniRemoteCommand { get; set; }
/// <summary>
/// Puts the Mini Remote on a tab: (tab id from IltSections.TabId, "" = the remote itself;
/// mode "show" / "hide" / "toggle", or "select" to switch tabs without showing it). Set by
/// RynthAiPlugin; returns the chat reply. Any thread (plain field writes).
/// </summary>
public Func<string, string, string>? MiniRemoteTabCommand { get; set; }
/// <summary>True while the Mini Remote is on screen (set by RynthAiPlugin).</summary>
public Func<bool>? MiniRemoteVisible { get; set; }
/// <summary>World is ILT-like and the server has at least one ILT feature on.</summary>
public bool Available => _ctx.Options.IsIltLikeWorld && _ctx.Options.AnyFeatureOn;
/// <summary>
/// Whether a section can be shown now. The universal tabs (Quests, Pets) and Character always
/// can (Character explains why the ILT tabs are idle and holds the Force-ILT override); the
/// rest need server features.
/// </summary>
public bool SectionAvailable(IltSection section) => section switch
{
IltSection.Character => true,
IltSection.Quests or IltSection.Pet => true,
IltSection.Banking => Available && !_ctx.Options.IsOff(IltFeature.Bank),
IltSection.Games => Available && Games.AnyGameAvailable,
_ => Available,
};
/// <summary>
/// The Mini Remote offers the Infinite Leaftide tabs: an ILT-like world (or the Force-ILT
/// override). The Character tab then always shows; the others follow
/// <see cref="SectionAvailable"/>. The universal tabs don't depend on this.
/// </summary>
public bool OffersTabs => _ctx.Options.IsIltLikeWorld;
/// <summary>
/// Whether the Mini Remote's tab bar shows <paramref name="section"/>: a universal tab always,
/// an Infinite Leaftide tab on an ILT world once <see cref="SectionAvailable"/>.
/// </summary>
public bool TabShown(IltSection section) =>
IltSections.IsUniversal(section) || (OffersTabs && IltSections.IsTab(section) && SectionAvailable(section));
/// <summary>Render thread: one Mini Remote ILT tab's body (MiniRemoteHud draws the tab bar).</summary>
public void RenderTab(IltSection section) => _ui.RenderTab(section);
/// <summary>Render thread: the Guardian panel's body (RynthPluginRenderEmbed "guardian").</summary>
public void RenderGuardianPanel() => _ui.RenderGuardianPanel();
/// <summary>The Force-ILT world override (world identity only; features still come from the server).</summary>
public bool ForceIltWorld
{
get => _ctx.State.ForceLeaftideFeatures;
set => _ctx.State.ForceLeaftideFeatures = value;
}
/// <summary>Re-asks the server which features are on (safe from the render thread: posted to the pump).</summary>
public void RequestOptionsRefresh() => _ctx.Post(() => _ctx.Options.Refresh(manual: true));
/// <summary>True when the cached options already say /myquests is off (skip the login refresh).</summary>
public bool SkipLoginQuestRefresh => _ctx.Options.IsIltLikeWorld && _ctx.Options.IsOff(IltFeature.Quests);
// ── Lifecycle ───────────────────────────────────────────────────────────
/// <summary>Login: remember the character, hook PetManager, schedule the options check, import UB data once.</summary>
public void OnLoginComplete(string charName, PetManager? petManager)
{
_ctx.CharName = charName ?? string.Empty;
RynthLog.Event(LogEvents.IltLogin, $"login: char='{_ctx.CharName}' world='{_ctx.Options.WorldName}'");
_ctx.Options.OnLoginComplete();
_ctx.Inventory.Reset();
Rates.Reset();
if (petManager != null)
{
petManager.AllowSummonOnEmpty = Pets.AllowSummonOnEmpty;
petManager.HoldSummons = Pets.HoldCombatSummons;
petManager.YieldPetForCombat = Pets.YieldPetForCombat;
}
HookQuestOutcome();
if (!_ctx.State.UbSidecarsImported && _ctx.CharName.Length > 0)
{
_ctx.State.UbSidecarsImported = true;
string world = _ctx.Options.WorldName;
Banking.ImportUb(tx => _ctx.Store.ImportUbSidecars(_ctx.State, tx, world, _ctx.CharName));
}
}
private void HookQuestOutcome()
{
if (_questOutcomeHooked) return;
var t = _quests();
if (t == null) return;
t.RefreshCompleted += () => _ctx.Options.NoteQuestTrackerOutcome(t.Disabled, t.Count);
_questOutcomeHooked = true;
}
/// <summary>Pump-thread tick.</summary>
public void Tick()
{
long now = IltHubContext.NowMs;
_ctx.DrainPosted();
_ctx.Capture.Tick();
_ctx.Options.Tick();
HookQuestOutcome();
// "Mini Remote on screen" gates bank auto-refresh and the gear / split-arrow scans.
_ctx.State.WindowVisible = MiniRemoteVisible?.Invoke() ?? false;
// One hint per session once the server confirms ILT features. The Mini Remote is separate
// from the main RynthAi panel, so say how to open it.
if (!_availabilityAnnounced && Available)
{
_availabilityAnnounced = true;
if (!_ctx.State.WindowVisible)
_ctx.Chat("[Mini Remote] ILT server features detected. Open the Mini Remote (bar button, /rc miniremote) for the ILT tabs.");
}
// The ILT features run only on ILT-like worlds; the universal ones (Quests, Pets) everywhere.
bool ilt = _ctx.Options.IsIltLikeWorld;
foreach (var f in _features)
{
if (!ilt && !IsUniversal(f)) continue;
try { f.Tick(now); }
catch (Exception ex) { RynthLog.Exception(CategoryOf(f), ex, $"{f.GetType().Name}.Tick"); }
}
// Expire an unanswered chat confirmation so a stale "/ra hub confirm" can't fire it later.
if (_pendingAction != null && now - _pendingAt > ConfirmWindowMs)
{
RynthLog.Event(LogEvents.IltConfirmation, $"confirmation expired: {_pendingLabel}");
_ctx.Chat($"[Mini Remote] Confirmation for '{_pendingLabel}' expired.");
ClearPending();
}
if (now - _lastSaveAt >= SaveIntervalMs)
{
_lastSaveAt = now;
_ctx.Store.SaveStateIfDirty(_ctx.State);
}
}
/// <summary>Pump-thread chat line. Returns true when the line should be hidden.</summary>
public bool OnChat(string text)
{
if (string.IsNullOrEmpty(text)) return false;
string line = text.TrimEnd('\r', '\n');
_ctx.Options.OnChatLine(line);
bool eat = _ctx.Capture.OnChatLine(line);
bool ilt = _ctx.Options.IsIltLikeWorld;
foreach (var f in _features)
{
if (!ilt && !IsUniversal(f)) continue;
try { eat |= f.OnChat(line); }
catch (Exception ex) { RynthLog.Exception(CategoryOf(f), ex, $"{f.GetType().Name}.OnChat"); }
}
return eat;
}
/// <summary>The feature behind a universal tab (Quests, Pets): it runs on every world.</summary>
private static bool IsUniversal(IIltFeature f) => f is IltQuests or IltPets;
/// <summary>Maps a feature module to its diagnostics category so its trace/exception lines land in its own file.</summary>
private static LogCat CategoryOf(IIltFeature f) => f switch
{
IltBanking => LogCat.IltBanking,
IltPets => LogCat.IltPets,
IltSessionRates => LogCat.IltRates,
IltQuests => LogCat.IltQuests,
IltProgression => LogCat.IltProgression,
IltGear or IltCharms => LogCat.IltGear,
IltGames => LogCat.IltGames,
_ => LogCat.IltHub,
};
/// <summary>Logout / teardown: stop automation and flush to disk.</summary>
public void OnLogout()
{
RynthLog.Event(LogEvents.IltLogout, $"logout: stopping features for '{_ctx.CharName}'");
ClearPending();
foreach (var f in _features)
{
try { f.OnLogout(); }
catch (Exception ex) { RynthLog.Exception(CategoryOf(f), ex, $"{f.GetType().Name}.OnLogout"); }
}
_ctx.Capture.Clear();
_ctx.Store.SaveStateIfDirty(_ctx.State);
}
/// <summary>
/// JSON for the engine Skills panel's Progression tab (RynthPluginGetProgressionJson).
/// "available" is false off ILT-like worlds; the panel then hides the ILT sections. Pump thread.
/// </summary>
public string BuildProgressionJson()
{
var sb = new System.Text.StringBuilder(2048);
sb.Append("{\"available\":").Append(Available ? "true" : "false");
sb.Append(",\"world\":\"").Append(RynthAiPlugin.JsonEscape(_ctx.Options.WorldName ?? string.Empty)).Append("\",");
Progression.AppendSnapshotJson(sb);
sb.Append('}');
return sb.ToString();
}
/// <summary>JSON for RynthPluginGetCharmsJson (an older engine's Settings "Charms Tracking" tab). Pump thread.</summary>
public string BuildCharmsJson() => Charms.BuildJson();
/// <summary>Render thread: Games HUD, quest favorites HUD and confirmation popups.</summary>
public void Render() => _ui.Render();
// ── Probe taps: reuse login-probe replies so tabs fill without extra commands ──
private void OnProbeReply(string key, IltChatResult r)
{
if (r.Lines.Count == 0) return;
switch (key)
{
case IltFeature.Aug: Progression.ApplyAugLines(r.Lines); break;
case IltFeature.Pets: Pets.ApplyRoster(false, r.Lines); break;
case IltFeature.Shinies: Pets.ApplyRoster(true, r.Lines); break;
case IltFeature.Qb: Quests.ApplyQbProbe(r.Lines); break;
// Bank lines are parsed passively by IltBanking.OnChat as they arrive.
}
}
// ── Commands ────────────────────────────────────────────────────────────
/// <summary>
/// "/ra hub [show|hide|toggle|open &lt;section&gt; [show|hide|toggle]|tab &lt;section|remote&gt;|refresh|
/// bank|status|force on|off|profile save|load|list ...|suit list|test|load ...]" (show/hide/toggle
/// drive the Mini Remote, open puts it on a tab, tab switches tabs without showing it),
/// "/ra quests [refresh|check &lt;regex&gt;|window|favhud]", "/ra pets [show|hide|toggle]",
/// "/ra bounty [show|hide|toggle]" (aliases bounties / bountys: RynthCore's ILT Bounties panel)
/// and "/ra guardian ..." (window: RynthCore's ILT Guardian panel; the rest IltGuardian.HandleCommand).
/// Pump thread. Returns false if not handled.
/// </summary>
public bool HandleCommand(string verb, string[] args)
{
RynthLog.Event(LogEvents.IltCommand, $"command: /ra {verb} {string.Join(" ", args)}".TrimEnd());
if (verb.Equals("quests", StringComparison.OrdinalIgnoreCase))
{
string sub = args.Length > 0 ? args[0].ToLowerInvariant() : "refresh";
string mode = args.Length > 1 ? args[1].ToLowerInvariant() : "toggle";
var cs = _ctx.State.Character;
switch (sub)
{
case "check" when args.Length > 1:
Quests.CheckCommand(string.Join(" ", args.Skip(1)));
break;
case "window":
OpenSection(IltSection.Quests, mode);
break;
case "favhud":
case "favorites":
cs.ShowQuestFavoritesHud = ResolveToggle(mode, cs.ShowQuestFavoritesHud);
_ctx.Chat(cs.ShowQuestFavoritesHud ? "[Mini Remote] Quest favorites HUD shown." : "[Mini Remote] Quest favorites HUD hidden.");
break;
default:
_ctx.Chat("[Mini Remote] " + Quests.RefreshQuests());
break;
}
return true;
}
if (verb.Equals("pets", StringComparison.OrdinalIgnoreCase))
{
// "/ra pets [show|hide|toggle]": same as "/ra hub open pets".
OpenSection(IltSection.Pet, args.Length > 0 ? args[0] : "toggle");
return true;
}
if (IsBountyVerb(verb))
{
// Bounties are the RynthILT plugin's (RynthCore's ILT button); open that panel.
OpenEnginePanel("bounties", "Bounties", args.Length > 0 ? args[0] : "toggle");
return true;
}
if (verb.Equals("guardian", StringComparison.OrdinalIgnoreCase))
{
// "/ra guardian window [show|hide|toggle]" opens RynthCore's ILT Guardian panel;
// everything else is the Guardian's.
if (args.Length > 0 && args[0].Equals("window", StringComparison.OrdinalIgnoreCase))
OpenEnginePanel("guardian", "Guardian", args.Length > 1 ? args[1] : "toggle");
else
Guardian.HandleCommand(args);
return true;
}
if (!verb.Equals("hub", StringComparison.OrdinalIgnoreCase)) return false;
string cmd = args.Length > 0 ? args[0].ToLowerInvariant() : "toggle";
string rest = args.Length > 1 ? string.Join(" ", args.Skip(1)) : string.Empty;
switch (cmd)
{
case "show":
case "hide":
case "toggle":
// The Mini Remote is the Hub's main window.
if (MiniRemoteCommand != null) _ctx.Chat(MiniRemoteCommand(cmd));
else _ctx.Chat("[Mini Remote] The Mini Remote is not available yet.");
break;
case "open":
if (args.Length > 1 && IsBountyVerb(args[1]))
{
OpenEnginePanel("bounties", "Bounties", args.Length > 2 ? args[2] : "toggle");
break;
}
if (args.Length < 2 || !IltSections.TryParse(args[1], out IltSection section))
{
_ctx.Chat("[Mini Remote] Usage: /ra hub open character|quests|pets|banking|gear|charms|games|guardian|bounties [show|hide|toggle]");
break;
}
OpenSection(section, args.Length > 2 ? args[2] : "toggle");
break;
case "tab":
// The engine's dashboard: it opens its Mini Remote window itself, so only switch tabs.
if (args.Length > 1 && IltSections.TryParse(args[1], out IltSection tab) && IltSections.IsTab(tab))
MiniRemoteTabCommand?.Invoke(IltSections.TabId(tab), "select");
else
MiniRemoteTabCommand?.Invoke(IltSections.RemoteTab, "select");
break;
case "refresh": _ctx.Options.Refresh(manual: true); break;
case "bank": Banking.RequestRefresh(quiet: false); break;
case "status": PrintStatus(); break;
case "force":
_ctx.State.ForceLeaftideFeatures = !rest.Equals("off", StringComparison.OrdinalIgnoreCase);
_ctx.Chat($"[Mini Remote] Force ILT world: {(_ctx.State.ForceLeaftideFeatures ? "on" : "off")}. Use /ra hub refresh to re-check the server.");
break;
case "profile": HandleProfile(args.Skip(1).ToArray()); break;
case "suit": HandleSuit(args.Skip(1).ToArray()); break;
case "clap": Gear.ChunkClap.ClapNow(manual: true); break;
case "attr": HandleAttr(args.Skip(1).ToArray()); break;
case "confirm": RunPending(); break;
case "cancel":
_ctx.Chat(_pendingAction != null ? $"[Mini Remote] Cancelled '{_pendingLabel}'." : "[Mini Remote] Nothing to cancel.");
ClearPending();
break;
default:
_ctx.Chat("[Mini Remote] /ra hub [show|hide|toggle] (Mini Remote)|refresh|bank|status|force on|off|clap|confirm|cancel");
_ctx.Chat("[Mini Remote] /ra hub open character|quests|pets|banking|gear|charms|games [show|hide|toggle] (Mini Remote tabs)");
_ctx.Chat("[Mini Remote] /ra hub profile list|save <name> [shared]|load <name> /ra hub suit list|test|load [name]");
_ctx.Chat("[Mini Remote] /ra hub attr run|stop|costs|status|auto on|off|every <min>|raise <stat> <n> (Skills panel > Progression)");
_ctx.Chat("[Mini Remote] /ra quests [refresh|check <regex>|window [show|hide]|favhud [show|hide]] /ra pets [show|hide]");
_ctx.Chat("[Mini Remote] /ra guardian [window|translate <text>|handin|stop|chat on|off|auto on|off|buy on|off|refresh|status] (window: ILT button > Guardian)");
_ctx.Chat("[Mini Remote] /ra bounty [show|hide|toggle] (RynthCore's ILT button > Bounties, /rc bounties)");
break;
}
return true;
}
/// <summary>"/ra hub attr ...": the attribute raiser from chat (same verbs as the Progression tab).</summary>
private void HandleAttr(string[] a)
{
var raiser = Progression.Attributes;
string sub = a.Length > 0 ? a[0].ToLowerInvariant() : "status";
switch (sub)
{
case "run": raiser.HandleRemote("attrrun", new[] { "attrrun" }); break;
case "stop": raiser.HandleRemote("attrstop", new[] { "attrstop" }); break;
case "costs": raiser.HandleRemote("attrcosts", new[] { "attrcosts" }); break;
case "auto": raiser.HandleRemote("attrauto", new[] { "attrauto", a.Length > 1 ? a[1] : "off" }); break;
case "every": raiser.HandleRemote("attrevery", new[] { "attrevery", a.Length > 1 ? a[1] : "5" }); break;
case "raise" when a.Length > 2: raiser.HandleRemote("attrraise", new[] { "attrraise", a[1], a[2] }); break;
default:
var c = _ctx.State.Character;
string blocked = raiser.Blocker() ?? "ready";
_ctx.Chat($"[Mini Remote] Attribute raiser: {blocked}; auto={(c.AttrAutoRaise ? $"on every {c.AttrAutoRaiseMinutes}m" : "off")} "
+ $"mode={(IltAttributeRaiser.Mode)c.AttrRaiseMode} keep={IltParse.Compact(c.AttrKeepXp)} "
+ $"stats={(c.AttrRaiseStats.Count > 0 ? string.Join(",", c.AttrOrder.Where(c.AttrRaiseStats.Contains)) : "none ticked")}");
return;
}
}
/// <summary>"/ra bounty", "/ra bounties" and the "/ra bountys" spelling all reach the Bounties panel.</summary>
public static bool IsBountyVerb(string verb)
=> verb.Equals("bounty", StringComparison.OrdinalIgnoreCase)
|| verb.Equals("bounties", StringComparison.OrdinalIgnoreCase)
|| verb.Equals("bountys", StringComparison.OrdinalIgnoreCase);
/// <summary>
/// Applies show / hide / toggle to a section: a Mini Remote tab, or for the Guardian
/// RynthCore's ILT panel. Says what happened.
/// </summary>
private void OpenSection(IltSection section, string mode)
{
if (!IltSections.IsTab(section))
{
OpenEnginePanel(IltSections.TabId(section), IltSections.Label(section), mode);
return;
}
string reply = MiniRemoteTabCommand?.Invoke(IltSections.TabId(section), mode) ?? "The Mini Remote is not available yet.";
if (!SectionAvailable(section) && !mode.Equals("hide", StringComparison.OrdinalIgnoreCase))
reply = $"The {IltSections.Label(section)} tab shows once the server reports that feature on.";
_ctx.Chat("[Mini Remote] " + reply);
}
/// <summary>
/// Opens / closes one of RynthCore's ILT panels ("/rc bounties|guardian [show|hide|toggle]")
/// through the engine's chat dispatcher. Pump thread.
/// </summary>
public void OpenEnginePanel(string rcVerb, string label, string mode)
{
string m = (mode ?? string.Empty).ToLowerInvariant() switch
{
"show" or "on" or "open" => "show",
"hide" or "off" or "close" => "hide",
_ => "toggle",
};
if (_ctx.Host.HasInvokeChatParser && _ctx.Host.InvokeChatParser($"/rc {rcVerb} {m}"))
return;
_ctx.Chat($"[Mini Remote] {label} is a RynthCore ILT panel: the bar's ILT button, or /rc {rcVerb}.");
}
/// <summary>"show"/"on" → true, "hide"/"off" → false, anything else flips <paramref name="current"/>.</summary>
private static bool ResolveToggle(string mode, bool current) => mode switch
{
"show" or "on" or "true" or "1" => true,
"hide" or "off" or "false" or "0" => false,
_ => !current,
};
private void PrintStatus()
{
var o = _ctx.Options;
_ctx.Chat($"[Mini Remote] World '{o.WorldName}' ILT={o.IsIltLikeWorld} force={_ctx.State.ForceLeaftideFeatures} source={(o.Source.Length > 0 ? o.Source : "none")} "
+ $"refreshed={(o.LastRefreshUtc == DateTime.MinValue ? "never" : o.LastRefreshUtc.ToLocalTime().ToString("t"))}");
var bits = o.SnapshotBits();
string on = string.Join(", ", bits.Where(b => b.Value == 1).Select(b => b.Key));
string off = string.Join(", ", bits.Where(b => b.Value == 0).Select(b => b.Key));
_ctx.Chat("[Mini Remote] on: " + (on.Length > 0 ? on : "-"));
_ctx.Chat("[Mini Remote] off: " + (off.Length > 0 ? off : "-"));
}
private void HandleProfile(string[] a)
{
string sub = a.Length > 0 ? a[0].ToLowerInvariant() : "list";
if (sub == "list")
{
var names = _ctx.Store.ListProfiles();
_ctx.Chat("[Mini Remote] Profiles: " + (names.Count > 0 ? string.Join(", ", names) : "(none)"));
return;
}
if (a.Length < 2) { _ctx.Chat("[Mini Remote] Usage: /ra hub profile save <name> [shared] | load <name>"); return; }
if (sub == "save")
{
bool shared = a.Length > 2 && a[2].Equals("shared", StringComparison.OrdinalIgnoreCase);
_ctx.Chat(_ctx.Store.SaveProfile(_ctx.State, a[1], shared, out string err)
? $"[Mini Remote] Saved {(shared ? "shared " : "")}profile '{a[1]}'." : "[Mini Remote] Save failed: " + err);
}
else if (sub == "load")
{
// Loading replaces the Hub's current settings, so it needs an explicit confirm.
string profile = a[1];
RequestConfirm($"load Hub profile '{profile}' (replaces current Hub settings)", () =>
_ctx.Chat(_ctx.Store.LoadProfile(_ctx.State, profile, out string err)
? $"[Mini Remote] Loaded profile '{profile}'." : "[Mini Remote] Load failed: " + err));
}
}
// ── Chat confirmations for destructive commands ─────────────────────────
/// <summary>How long a "/ra hub confirm" stays valid after the prompt.</summary>
private const long ConfirmWindowMs = 20000;
private string? _pendingLabel;
private Action? _pendingAction;
private long _pendingAt;
/// <summary>Arms a single pending action; a newer request replaces an older one.</summary>
private void RequestConfirm(string label, Action action)
{
_pendingLabel = label;
_pendingAction = action;
_pendingAt = IltHubContext.NowMs;
RynthLog.Event(LogEvents.IltConfirmation, $"confirmation requested: {label}");
_ctx.Chat($"[Mini Remote] About to {label}. Type /ra hub confirm within {ConfirmWindowMs / 1000} s, or /ra hub cancel.");
}
/// <summary>Runs the pending action if one is armed and still inside its window.</summary>
private void RunPending()
{
var action = _pendingAction;
string? label = _pendingLabel;
bool fresh = action != null && IltHubContext.NowMs - _pendingAt <= ConfirmWindowMs;
ClearPending();
if (!fresh || action == null) { _ctx.Chat("[Mini Remote] Nothing to confirm."); return; }
RynthLog.Event(LogEvents.IltConfirmation, $"confirmed: {label}");
try { action(); }
catch (Exception ex) { RynthLog.Exception(LogCat.IltHub, ex, $"confirmed action '{label}'"); }
}
private void ClearPending()
{
_pendingAction = null;
_pendingLabel = null;
_pendingAt = 0;
}
private void HandleSuit(string[] a)
{
string sub = a.Length > 0 ? a[0].ToLowerInvariant() : "list";
string? name = a.Length > 1 ? string.Join(" ", a.Skip(1)) : null;
switch (sub)
{
case "list":
var list = Gear.Suits.ListProfiles();
_ctx.Chat("[Mini Remote] Suits: " + (list.Count > 0 ? string.Join(", ", list.Select(p => p.Name)) : "(none)"));
break;
case "test":
foreach (string l in Gear.Suits.Test(name)) _ctx.Chat("[Mini Remote] " + l);
break;
case "load":
// Equipping a suit swaps gear mid-session, so it needs an explicit confirm.
RequestConfirm($"equip suit '{name ?? "(auto)"}'", () => _ctx.Chat("[Mini Remote] " + Gear.Suits.Load(name)));
break;
default:
_ctx.Chat("[Mini Remote] Usage: /ra hub suit list|test [name]|load [name]");
break;
}
}
}

View file

@ -0,0 +1,292 @@
// IltHubState.cs — Persisted per-character state for the ILT Hub (Infinite Leaftide tools).
//
// Lives in <charFolder>\ilt-hub.json, deliberately separate from the combat settings
// profile (Default.json / /ra settings) so ILT data never leaks into combat profiles and
// non-ILT characters stay untouched. Serialized with the NativeAOT source-generated
// RynthAiJsonContext (IncludeFields = true), so plain public fields are used throughout.
using System;
using System.Collections.Generic;
namespace RynthCore.Plugin.RynthAi.IltHub;
/// <summary>Root of everything the Hub remembers between sessions.</summary>
public sealed class IltHubState
{
/// <summary>Bumped when the shape changes in a way that needs a migration.</summary>
public int SchemaVersion = 1;
// ── Window / shell ──────────────────────────────────────────────────────
/// <summary>
/// Hub UI on screen: the Mini Remote or any ILT section window (IltHubController.Tick keeps it
/// current). Bank auto-refresh and the gear / split-arrow scans run only while it is true.
/// </summary>
public bool WindowVisible;
/// <summary>Unused since the tabbed Hub window was retired; kept so old files still load.</summary>
public int SelectedTab;
public bool GamesHudVisible = true;
/// <summary>
/// "This world is an ACECustom/ILT shard even though its name isn't InfiniteLeaftide."
/// World-identity override ONLY: it makes the Hub ask the server for its options, it
/// never turns a feature on by itself.
/// </summary>
public bool ForceLeaftideFeatures;
/// <summary>True once the one-time UtilityBelt sidecar import has run for this character.</summary>
public bool UbSidecarsImported;
/// <summary>Last-seen server feature bits. Cache only — overwritten by every login refresh.</summary>
public IltServerOptionsSnapshot ServerOptions = new();
public IltBankState Bank = new();
public IltPetState Pet = new();
public IltCharacterState Character = new();
public IltGearState Gear = new();
public IltGamesState Games = new();
public IltGuardianState Guardian = new();
}
/// <summary>Cached result of the server-options check (see IltServerOptions).</summary>
public sealed class IltServerOptionsSnapshot
{
public string WorldName = string.Empty;
/// <summary>"ilt-features" (structured dump), "probe" (command probing) or "" (never refreshed).</summary>
public string Source = string.Empty;
public DateTime LastRefreshUtc = DateTime.MinValue;
/// <summary>Feature key → -1 unknown, 0 off, 1 on.</summary>
public Dictionary<string, int> Bits = new(StringComparer.OrdinalIgnoreCase);
}
// ── Banking ─────────────────────────────────────────────────────────────────
public sealed class IltBankState
{
public long Pyreals;
public long Luminance;
public long LegendaryKeys;
public long MythicalKeys;
public long EnlightenedCoins;
public long WeaklyEnlightenedCoins;
/// <summary>Bound to the character: deposit and withdraw only, never transferred.</summary>
public long PrestigeCoins;
public DateTime LastUpdated = DateTime.MinValue;
/// <summary>Last transfer recipient typed into the transfer form.</summary>
public string TransferTarget = string.Empty;
public int TransferCurrencyIndex;
/// <summary>Deposit / withdraw form choices (IltBankCommands.Deposits / Withdrawals / NoteDenominations).</summary>
public int DepositIndex;
public int WithdrawIndex;
public int WithdrawNoteIndex = 9;
/// <summary>Re-issue /bank every N seconds while the Hub is open (0 = manual only).</summary>
public int AutoRefreshSeconds = 120;
}
/// <summary>One "Transferred …" / "Received …" bank line seen in chat.</summary>
public sealed class IltBankTransaction
{
public DateTime Timestamp;
/// <summary>"Sent" or "Received".</summary>
public string Type = string.Empty;
public string Currency = string.Empty;
public long Amount;
public string OtherPlayer = string.Empty;
public string Description = string.Empty;
}
// ── Pet ─────────────────────────────────────────────────────────────────────
public sealed class IltPetState
{
// Healing-pet automation (UB "HealingBuddy" subset).
public bool HealingEnabled;
/// <summary>Exact name of the heal-pet essence to use; empty = auto-detect (Healing Buddy / Dule box).</summary>
public string HealPetName = string.Empty;
public int HealthThresholdPercent = 80;
/// <summary>Do not summon when current HP is below this (summoning mid-death wastes the use). 0 = off.</summary>
public int MinHealthPoints = 100;
public bool AutoDespawnAfterHeal = true;
public int RespawnDelaySeconds = 2;
public int PetTimeoutSeconds = 30;
/// <summary>
/// Allow a combat summon from an EMPTY essence when the Summon Essence Refill Charm is
/// active (server refills from banked pyreals). Still requires the server flag to be on.
/// </summary>
public bool UsePyrealRefillPath;
/// <summary>Last captured /pets and /shinies rosters (display only).</summary>
public List<string> PetLog = new();
public List<string> ShinyLog = new();
// ── Pet roster (UB Pets-tab style) ──
/// <summary>Roster type shown in the Pet tab (IltPetKind: 0 Combat, 1 Healing, 2 Cosmetic).</summary>
public int RosterKind;
/// <summary>Roster sort (IltPetSort: 0 Priority, 1 Bond, 2 Potency, 3 Breed ready, 4 Level, 5 Uses, 6 Name).</summary>
public int RosterSort;
/// <summary>User type overrides by essence name; essences not listed are auto-classified.</summary>
public List<IltPetAssignment> Assignments = new();
/// <summary>Essence name of the chosen cosmetic (display) pet; empty = none.</summary>
public string CosmeticPetName = string.Empty;
/// <summary>Keep the cosmetic pet summoned while in peace mode; it is dismissed when a combat pet is needed.</summary>
public bool KeepCosmeticOut;
/// <summary>Seconds to wait before re-summoning the cosmetic pet after it despawns.</summary>
public int CosmeticRespawnSeconds = 15;
}
/// <summary>A user's choice of summon type for one essence (matched by name, case-insensitive).</summary>
public sealed class IltPetAssignment
{
public string Name = string.Empty;
/// <summary>IltPetKind as int (0 Combat, 1 Healing, 2 Cosmetic).</summary>
public int Kind;
}
// ── Character ───────────────────────────────────────────────────────────────
public sealed class IltCharacterState
{
/// <summary>Item → coin conversion table used by the session-rates strip.</summary>
public List<IltItemConversion> ItemConversions = new()
{
new IltItemConversion { ItemName = "Strawberry Jam Jar", ItemsPerConversion = 100, CoinsPerConversion = 10 },
new IltItemConversion { ItemName = "Ancient Pyreal", ItemsPerConversion = 100, CoinsPerConversion = 37 },
};
/// <summary>Augmentation planner targets, keyed by aug type (lowercase).</summary>
public Dictionary<string, int> AugTargets = new(StringComparer.OrdinalIgnoreCase);
/// <summary>Luminance price of one Enlightened Coin (planner math only; 0 = don't price coins).</summary>
public long LumPerEnlightenedCoin;
/// <summary>Enlightenment planner target level (0 = current + 5).</summary>
public int EnlTargetLevel;
public int EnlightenedCoinsPerToken = 20;
/// <summary>
/// Auto-enlighten preference. Even when true it stays DISARMED each session until the
/// player confirms in the Hub, and the server's own Yes/No dialog is never auto-clicked.
/// </summary>
public bool AutoEnlightenEnabled;
public int AutoEnlightenCheckSeconds = 30;
/// <summary>Spend unassigned XP with /attr before sending /enl (enlightening wipes unspent XP).</summary>
public bool AutoEnlightenSpendXpFirst;
// ── Attribute raiser (IltAttributeRaiser; Skills panel > Progression) ──
/// <summary>Spend unassigned XP on the ticked attributes/vitals every AttrAutoRaiseMinutes.</summary>
public bool AttrAutoRaise;
public int AttrAutoRaiseMinutes = 5;
/// <summary>IltAttributeRaiser.Mode: 0 priority (top of the order first), 1 round robin, 2 cheapest first.</summary>
public int AttrRaiseMode;
/// <summary>Unassigned XP the raiser never spends.</summary>
public long AttrKeepXp;
/// <summary>/attr abbreviations in raise-priority order (all nine; repaired on load).</summary>
public List<string> AttrOrder = new(IltAttributeRaiser.DefaultOrder);
/// <summary>/attr abbreviations the raiser may spend on ("Raise now" and auto-raise).</summary>
public List<string> AttrRaiseStats = new();
/// <summary>Quest Tracker search box contents.</summary>
public string QuestFilter = string.Empty;
public string QbFilter = string.Empty;
/// <summary>Starred quest flag keys (lowercase), shown on the floating favorites HUD.</summary>
public List<string> QuestFavorites = new();
/// <summary>Quest tracker lists starred quests only.</summary>
public bool QuestFavoritesOnly;
/// <summary>Floating quest favorites HUD is shown.</summary>
public bool ShowQuestFavoritesHud;
public bool QuestFavoritesHudLocked;
// The ILT sections are Mini Remote tabs now (HudState.MiniRemoteTab); the old per-section
// "window open" flags in older files are ignored on load.
/// <summary>
/// Registry charms this character has carried, keyed by charm name. Lets the Charms Tracking
/// tab report "acquired" for charms that are now in storage (the client only sees carried items).
/// </summary>
public Dictionary<string, IltCharmSeen> CharmsSeen = new(StringComparer.OrdinalIgnoreCase);
}
/// <summary>Last time a charm was seen in the character's possession, with its best tier.</summary>
public sealed class IltCharmSeen
{
public int Tier;
public int MaxTier;
public DateTime LastSeenUtc;
}
public sealed class IltItemConversion
{
public string ItemName = string.Empty;
public int ItemsPerConversion = 100;
public int CoinsPerConversion;
}
// ── Gear ────────────────────────────────────────────────────────────────────
public sealed class IltGearState
{
// Dispel (Rune of Dispel on harmful debuffs)
public bool AutoDispel;
public int DispelCooldownSeconds = 10;
/// <summary>Spell-name substrings that are ALWAYS dispelled.</summary>
public List<string> DispelInclusions = new();
/// <summary>Spell-name substrings that are NEVER dispelled.</summary>
public List<string> DispelExclusions = new();
// Surging Strength (Empowered Volcanic Ember keeper)
public bool SurgingStrength;
public int SurgingCooldownSeconds = 15;
// Aetheria / corrupted-weapon chunking
public bool AutoChunkAetheria;
public bool AutoChunkCorrupted;
public bool ChunkInCombat;
public int ChunkIntervalMs = 2000;
/// <summary>Only chunk aetheria whose max level is below this (Coalesced always chunks).</summary>
public int ChunkAetheriaUnderLevel = 4;
// Auto-clap (/clap all)
public bool AutoClap;
public int ClapIntervalMinutes = 30;
// Guardian Hand charm (WCID unpublished — name match until set)
public uint GuardianHandWcid;
public string GuardianHandName = "Guardian Hand";
// Split arrows (White Quartz imbue on missile weapons)
public int SplitArrowTarget = 3;
public bool SplitIgnoreImbued = true;
// Equipment profiles (.utl suits) and VTank .usd import
public string LastEquipProfile = string.Empty;
public string LastUsdPath = string.Empty;
}
// ── Games ───────────────────────────────────────────────────────────────────
public sealed class IltGamesState
{
public long BlackjackBet = 1_000_000;
public long FellowshipBlackjackBet = 1_000_000;
public int PowerballQuantity = 1;
}
// ── Guardian (Temple of Enlightenment) ──────────────────────────────────────
public sealed class IltGuardianState
{
/// <summary>Translate incoming guardian tells and show the answer (Guardian window + Mini Remote).</summary>
public bool AutoDetectFromChat = true;
/// <summary>After a chat answer, give the item to the guardian automatically.</summary>
public bool AutoHandIn;
/// <summary>Temple guardian only: buy one of the item from the nearest vendor when none is carried.</summary>
public bool BuyMissingFromVendor = true;
/// <summary>Assumed attribute turn-in cooldown when only /qb wait stamps are known (hours).</summary>
public int CooldownHoursAssumed = 20;
/// <summary>Turn-ins counted from /qb wait-stamp transitions, keyed by attribute (fallback when /myquests lacks the flag).</summary>
public Dictionary<string, int> TurnInCounts = new(StringComparer.OrdinalIgnoreCase);
/// <summary>Estimated end of each attribute's cooldown (UTC), keyed by attribute (same fallback).</summary>
public Dictionary<string, DateTime> CooldownUntilUtc = new(StringComparer.OrdinalIgnoreCase);
}

View file

@ -0,0 +1,409 @@
// IltHubStore.cs — Disk persistence for the ILT Hub.
//
// Files (all under the per-character settings folder the dashboard already uses):
// <charFolder>\ilt-hub.json live Hub state (IltHubState)
// <charFolder>\ilt-hub-transactions.json bank transaction log (capped)
// <charFolder>\ilt-hub-profiles\<n>.json named per-character Hub profiles
// <root>\IltHubProfiles\<n>.json named profiles shared by every character
// Saves are dirty-checked (the serialized JSON is compared to what was last written) so
// the periodic save in Tick costs nothing when nothing changed. A one-time import pulls
// UtilityBelt's bankdata sidecars so players keep their balances and history.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.Json;
using RynthCore.PluginSdk;
using RynthCore.Install;
namespace RynthCore.Plugin.RynthAi.IltHub;
internal sealed class IltHubStore
{
/// <summary>Maximum bank transactions kept on disk (oldest dropped first).</summary>
public const int MaxTransactions = 1000;
/// <summary>Shared root (<SuiteDir>\RynthAi) for profiles usable by every character.</summary>
public static readonly string SharedRoot = RynthInstallPaths.RynthAiDir;
private readonly RynthCoreHost _host;
private readonly string _charFolder;
private string _lastStateJson = string.Empty;
private string _lastTxJson = string.Empty;
public IltHubStore(RynthCoreHost host, string charFolder)
{
_host = host;
_charFolder = charFolder ?? string.Empty;
}
public string CharFolder => _charFolder;
private string StatePath => Path.Combine(_charFolder, "ilt-hub.json");
private string TxPath => Path.Combine(_charFolder, "ilt-hub-transactions.json");
private string CharProfileDir => Path.Combine(_charFolder, "ilt-hub-profiles");
private static string SharedProfileDir => Path.Combine(SharedRoot, "IltHubProfiles");
// ── State ───────────────────────────────────────────────────────────────
/// <summary>Loads the live state, returning defaults when the file is missing or unreadable.</summary>
public IltHubState LoadState()
{
try
{
if (_charFolder.Length > 0 && File.Exists(StatePath))
{
string json = File.ReadAllText(StatePath);
var s = JsonSerializer.Deserialize(json, RynthAiJsonContext.Default.IltHubState);
if (s != null)
{
Normalize(s);
_lastStateJson = json;
return s;
}
}
}
catch (Exception ex) { RynthLog.Exception(LogCat.IltStore, ex, $"load {StatePath}"); }
return new IltHubState();
}
/// <summary>Writes the state only when its JSON differs from the last write.</summary>
public void SaveStateIfDirty(IltHubState state)
{
if (_charFolder.Length == 0) return;
try
{
string json = JsonSerializer.Serialize(state, RynthAiJsonContext.Default.IltHubState);
if (json == _lastStateJson) return;
Directory.CreateDirectory(_charFolder);
WriteAtomic(StatePath, json);
_lastStateJson = json;
}
catch (Exception ex) { RynthLog.Exception(LogCat.IltStore, ex, $"save {StatePath}"); }
}
/// <summary>Repairs null collections / out-of-range values after deserialization.</summary>
private static void Normalize(IltHubState s)
{
s.ServerOptions ??= new IltServerOptionsSnapshot();
s.ServerOptions.Bits = new Dictionary<string, int>(s.ServerOptions.Bits ?? new(), StringComparer.OrdinalIgnoreCase);
s.Bank ??= new IltBankState();
s.Pet ??= new IltPetState();
s.Pet.PetLog ??= new();
s.Pet.ShinyLog ??= new();
s.Pet.Assignments ??= new();
s.Pet.Assignments.RemoveAll(a => a == null || string.IsNullOrWhiteSpace(a.Name));
s.Pet.CosmeticPetName ??= string.Empty;
s.Pet.RosterKind = Math.Clamp(s.Pet.RosterKind, 0, 2);
s.Pet.RosterSort = Math.Clamp(s.Pet.RosterSort, 0, 6);
s.Pet.CosmeticRespawnSeconds = Math.Clamp(s.Pet.CosmeticRespawnSeconds, 5, 600);
s.Character ??= new IltCharacterState();
s.Character.ItemConversions ??= new();
s.Character.QuestFavorites ??= new();
s.Character.QuestFavorites.RemoveAll(string.IsNullOrWhiteSpace);
s.Character.AugTargets = new Dictionary<string, int>(s.Character.AugTargets ?? new(), StringComparer.OrdinalIgnoreCase);
s.Character.AttrOrder = IltAttributeRaiser.RepairOrder(s.Character.AttrOrder);
s.Character.AttrRaiseStats = IltAttributeRaiser.RepairSelection(s.Character.AttrRaiseStats);
s.Character.AttrAutoRaiseMinutes = Math.Clamp(s.Character.AttrAutoRaiseMinutes, 1, 1440);
s.Character.AttrRaiseMode = Math.Clamp(s.Character.AttrRaiseMode, 0, 2);
s.Character.AttrKeepXp = Math.Max(0, s.Character.AttrKeepXp);
s.Character.CharmsSeen = new Dictionary<string, IltCharmSeen>(s.Character.CharmsSeen ?? new(), StringComparer.OrdinalIgnoreCase);
s.Gear ??= new IltGearState();
s.Gear.DispelInclusions ??= new();
s.Gear.DispelExclusions ??= new();
s.Games ??= new IltGamesState();
s.Guardian ??= new IltGuardianState();
s.Guardian.TurnInCounts = new Dictionary<string, int>(s.Guardian.TurnInCounts ?? new(), StringComparer.OrdinalIgnoreCase);
s.Guardian.CooldownUntilUtc = new Dictionary<string, DateTime>(s.Guardian.CooldownUntilUtc ?? new(), StringComparer.OrdinalIgnoreCase);
s.Guardian.CooldownHoursAssumed = Math.Clamp(s.Guardian.CooldownHoursAssumed, 1, 72);
s.SelectedTab = Math.Clamp(s.SelectedTab, 0, 4);
s.Gear.SplitArrowTarget = Math.Clamp(s.Gear.SplitArrowTarget, 0, 10);
}
// ── Transactions ────────────────────────────────────────────────────────
public List<IltBankTransaction> LoadTransactions()
{
try
{
if (_charFolder.Length > 0 && File.Exists(TxPath))
{
string json = File.ReadAllText(TxPath);
var list = JsonSerializer.Deserialize(json, RynthAiJsonContext.Default.IltBankTransactionList);
if (list != null) { _lastTxJson = json; return list; }
}
}
catch (Exception ex) { RynthLog.Exception(LogCat.IltStore, ex, $"load {TxPath}"); }
return new List<IltBankTransaction>();
}
public void SaveTransactionsIfDirty(List<IltBankTransaction> list)
{
if (_charFolder.Length == 0) return;
try
{
if (list.Count > MaxTransactions)
list.RemoveRange(0, list.Count - MaxTransactions);
string json = JsonSerializer.Serialize(list, RynthAiJsonContext.Default.IltBankTransactionList);
if (json == _lastTxJson) return;
Directory.CreateDirectory(_charFolder);
WriteAtomic(TxPath, json);
_lastTxJson = json;
}
catch (Exception ex) { RynthLog.Exception(LogCat.IltStore, ex, $"save {TxPath}"); }
}
// ── Profiles ────────────────────────────────────────────────────────────
/// <summary>Lists profile names. Shared ones are prefixed "shared:".</summary>
public List<string> ListProfiles()
{
var names = new List<string>();
try
{
if (Directory.Exists(CharProfileDir))
names.AddRange(Directory.GetFiles(CharProfileDir, "*.json").Select(Path.GetFileNameWithoutExtension).OfType<string>());
if (Directory.Exists(SharedProfileDir))
names.AddRange(Directory.GetFiles(SharedProfileDir, "*.json").Select(p => "shared:" + Path.GetFileNameWithoutExtension(p)));
}
catch (Exception ex) { RynthLog.Exception(LogCat.IltStore, ex, $"list profiles"); }
names.Sort(StringComparer.OrdinalIgnoreCase);
return names;
}
/// <summary>Saves the preference parts of <paramref name="state"/> as a named profile.</summary>
public bool SaveProfile(IltHubState state, string name, bool shared, out string error)
{
error = string.Empty;
string safe = SanitizeName(name);
if (safe.Length == 0) { error = "Profile name is empty."; return false; }
try
{
string dir = shared ? SharedProfileDir : CharProfileDir;
Directory.CreateDirectory(dir);
var copy = Clone(state);
StripRuntime(copy);
WriteAtomic(Path.Combine(dir, safe + ".json"), JsonSerializer.Serialize(copy, RynthAiJsonContext.Default.IltHubState));
return true;
}
catch (Exception ex) { error = ex.Message; return false; }
}
/// <summary>
/// Loads a profile onto <paramref name="target"/>, keeping runtime data (balances,
/// server bits, rosters, import flag) from the current state.
/// </summary>
public bool LoadProfile(IltHubState target, string name, out string error)
{
error = string.Empty;
bool shared = name.StartsWith("shared:", StringComparison.OrdinalIgnoreCase);
string safe = SanitizeName(shared ? name.Substring(7) : name);
string path = Path.Combine(shared ? SharedProfileDir : CharProfileDir, safe + ".json");
try
{
if (!File.Exists(path)) { error = $"Profile not found: {name}"; return false; }
var p = JsonSerializer.Deserialize(File.ReadAllText(path), RynthAiJsonContext.Default.IltHubState);
if (p == null) { error = "Profile file is empty."; return false; }
Normalize(p);
target.Pet = KeepRosters(p.Pet, target.Pet);
target.Character = p.Character;
target.Gear = p.Gear;
target.Games = p.Games;
target.Bank.AutoRefreshSeconds = p.Bank.AutoRefreshSeconds;
target.ForceLeaftideFeatures = p.ForceLeaftideFeatures;
target.GamesHudVisible = p.GamesHudVisible;
return true;
}
catch (Exception ex) { error = ex.Message; return false; }
}
private static IltPetState KeepRosters(IltPetState incoming, IltPetState current)
{
incoming.PetLog = current.PetLog;
incoming.ShinyLog = current.ShinyLog;
return incoming;
}
private static IltHubState Clone(IltHubState s)
=> JsonSerializer.Deserialize(JsonSerializer.Serialize(s, RynthAiJsonContext.Default.IltHubState),
RynthAiJsonContext.Default.IltHubState) ?? new IltHubState();
/// <summary>Removes character-specific runtime data before a profile is written.</summary>
private static void StripRuntime(IltHubState s)
{
s.ServerOptions = new IltServerOptionsSnapshot();
var keepRefresh = s.Bank.AutoRefreshSeconds;
s.Bank = new IltBankState { AutoRefreshSeconds = keepRefresh };
s.Pet.PetLog = new();
s.Pet.ShinyLog = new();
s.UbSidecarsImported = false;
s.WindowVisible = false;
}
private static string SanitizeName(string name)
{
var invalid = Path.GetInvalidFileNameChars();
return new string((name ?? string.Empty).Trim().Where(c => !invalid.Contains(c)).ToArray());
}
// ── UtilityBelt sidecar import ──────────────────────────────────────────
/// <summary>
/// One-time import of UB's bankdata (balances, transactions) and item conversions.
/// Searches Documents\Decal Plugins\UtilityBelt\&lt;world&gt;\&lt;char&gt;; when the world is
/// unknown every world folder containing the character is tried. Returns a summary.
/// </summary>
public string ImportUbSidecars(IltHubState state, List<IltBankTransaction> txLog, string world, string charName)
{
if (string.IsNullOrWhiteSpace(charName)) return "character name unknown";
string ubRoot = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "Decal Plugins", "UtilityBelt");
if (!Directory.Exists(ubRoot)) return "no UtilityBelt folder";
var charDirs = new List<string>();
if (!string.IsNullOrWhiteSpace(world))
charDirs.Add(Path.Combine(ubRoot, world, charName));
try
{
foreach (string w in Directory.GetDirectories(ubRoot))
{
string d = Path.Combine(w, charName);
if (!charDirs.Contains(d, StringComparer.OrdinalIgnoreCase)) charDirs.Add(d);
}
}
catch { /* unreadable Documents subfolder: fall through with what we have */ }
foreach (string dir in charDirs)
{
string bankDir = Path.Combine(dir, "bankdata");
if (!Directory.Exists(bankDir) && !Directory.Exists(dir)) continue;
int parts = 0;
parts += ImportBalances(Path.Combine(bankDir, "bankbalances.json"), state.Bank) ? 1 : 0;
int tx = ImportTransactions(Path.Combine(bankDir, "transactions.json"), txLog);
int conv = ImportConversions(new[]
{
Path.Combine(bankDir, "itemconversions.json"),
Path.Combine(dir, "itemconversions.json"),
}, state.Character.ItemConversions);
if (parts + tx + conv > 0)
return $"imported from {dir}: balances {(parts > 0 ? "yes" : "no")}, {tx} transactions, {conv} conversions";
}
return "no UtilityBelt bank data found for " + charName;
}
private bool ImportBalances(string path, IltBankState bank)
{
if (!File.Exists(path)) return false;
try
{
using var doc = JsonDocument.Parse(File.ReadAllText(path));
var root = doc.RootElement;
if (root.ValueKind != JsonValueKind.Object) return false;
bank.Pyreals = ReadLong(root, "Pyreals");
bank.Luminance = ReadLong(root, "Luminance");
bank.LegendaryKeys = ReadLong(root, "LegendaryKeys");
bank.MythicalKeys = ReadLong(root, "MythicalKeys");
bank.EnlightenedCoins = ReadLong(root, "EnlightenedCoins");
bank.WeaklyEnlightenedCoins = ReadLong(root, "WeaklyEnlightenedCoins");
if (TryGetProp(root, "LastUpdated", out var lu) && lu.ValueKind == JsonValueKind.String && lu.TryGetDateTime(out var dt))
bank.LastUpdated = dt;
return true;
}
catch (Exception ex) { RynthLog.Exception(LogCat.IltStore, ex, $"UB balances import"); return false; }
}
private int ImportTransactions(string path, List<IltBankTransaction> txLog)
{
if (!File.Exists(path)) return 0;
try
{
using var doc = JsonDocument.Parse(File.ReadAllText(path));
if (doc.RootElement.ValueKind != JsonValueKind.Array) return 0;
int added = 0;
foreach (var e in doc.RootElement.EnumerateArray())
{
if (e.ValueKind != JsonValueKind.Object) continue;
var t = new IltBankTransaction
{
Type = ReadString(e, "Type"),
Currency = ReadString(e, "Currency"),
Amount = ReadLong(e, "Amount"),
OtherPlayer = ReadString(e, "OtherPlayer"),
Description = ReadString(e, "Description"),
};
if (TryGetProp(e, "Timestamp", out var ts) && ts.ValueKind == JsonValueKind.String && ts.TryGetDateTime(out var dt))
t.Timestamp = dt;
// Skip exact duplicates so re-running the import can't double the log.
if (txLog.Any(x => x.Timestamp == t.Timestamp && x.Amount == t.Amount && x.OtherPlayer == t.OtherPlayer)) continue;
txLog.Add(t);
added++;
}
txLog.Sort((a, b) => a.Timestamp.CompareTo(b.Timestamp));
return added;
}
catch (Exception ex) { RynthLog.Exception(LogCat.IltStore, ex, $"UB transactions import"); return 0; }
}
private int ImportConversions(string[] paths, List<IltItemConversion> table)
{
foreach (string path in paths)
{
if (!File.Exists(path)) continue;
try
{
using var doc = JsonDocument.Parse(File.ReadAllText(path));
if (doc.RootElement.ValueKind != JsonValueKind.Array) continue;
int added = 0;
foreach (var e in doc.RootElement.EnumerateArray())
{
string name = ReadString(e, "ItemName");
if (name.Length == 0) continue;
var existing = table.FirstOrDefault(c => c.ItemName.Equals(name, StringComparison.OrdinalIgnoreCase));
if (existing == null) { existing = new IltItemConversion { ItemName = name }; table.Add(existing); added++; }
existing.ItemsPerConversion = Math.Max(1, (int)ReadLong(e, "ItemsPerConversion"));
existing.CoinsPerConversion = (int)ReadLong(e, "CoinsPerConversion");
}
return added;
}
catch (Exception ex) { RynthLog.Exception(LogCat.IltStore, ex, $"UB conversions import"); }
}
return 0;
}
// ── JSON helpers (case-insensitive property access) ─────────────────────
private static bool TryGetProp(JsonElement obj, string name, out JsonElement value)
{
foreach (var p in obj.EnumerateObject())
if (p.Name.Equals(name, StringComparison.OrdinalIgnoreCase)) { value = p.Value; return true; }
value = default;
return false;
}
private static long ReadLong(JsonElement obj, string name)
{
if (!TryGetProp(obj, name, out var v)) return 0;
if (v.ValueKind == JsonValueKind.Number && v.TryGetInt64(out long l)) return l;
if (v.ValueKind == JsonValueKind.String) return IltParse.ParseLeadingLong(v.GetString() ?? string.Empty);
return 0;
}
private static string ReadString(JsonElement obj, string name)
{
if (!TryGetProp(obj, name, out var v)) return string.Empty;
return v.ValueKind switch
{
JsonValueKind.String => v.GetString() ?? string.Empty,
JsonValueKind.Number => v.GetRawText(),
_ => string.Empty,
};
}
/// <summary>Write-then-rename so a crash mid-write never leaves a truncated file.</summary>
private static void WriteAtomic(string path, string contents)
{
string tmp = path + ".tmp";
File.WriteAllText(tmp, contents);
File.Move(tmp, path, overwrite: true);
}
}

View file

@ -0,0 +1,234 @@
// IltHubUi.cs — The ILT sections' ImGui bodies (render thread only).
//
// The ILT sections are tabs of the Mini Remote (MiniRemoteHud draws the tab bar and calls
// RenderTab): Character (world status, Force-ILT, profiles, session rates), Quests (IltQuests),
// Pets, Banking, Gear, Charms and Games. A tab is offered only while the server reports its feature on.
// The Guardian (IltGuardian: Temple riddle translator, hand-in, attribute turn-in tracker) is a
// RynthCore ILT panel instead (the bar's ILT button, next to Bounties), drawn through
// RenderGuardianPanel. Render() keeps the floating extras: the Games HUD, the quest favorites HUD
// and the confirmation modal. Augmentations / Enlightenment / XP planning live on the engine
// Skills panel. All AC actions go through IltHubContext.Post / Confirm so nothing here touches
// the game directly.
using System;
using System.Numerics;
using ImGuiNET;
using RynthCore.Plugin.RynthAi.LegacyUi;
namespace RynthCore.Plugin.RynthAi.IltHub;
internal sealed class IltHubUi
{
private const string ConfirmPopupId = "Confirm##iltconfirm";
private readonly IltHubController _hub;
private readonly IltHubContext _ctx;
private IltConfirmRequest? _confirm;
private bool _confirmOpened;
private string _profileName = string.Empty;
private bool _profileShared;
private string[] _profileList = Array.Empty<string>();
private int _profileIdx;
// The last tab body drawn (for one shown log event per tab change); -1 = none yet.
private int _lastTabLogged = -1;
public IltHubUi(IltHubController hub, IltHubContext ctx)
{
_hub = hub;
_ctx = ctx;
}
/// <summary>The floating extras: Games HUD, quest favorites HUD and the confirmation modal.</summary>
public void Render()
{
_hub.Games.RenderHud();
_hub.Quests.RenderFloatingWindows();
RenderConfirm();
}
/// <summary>
/// Size of a Mini Remote tab's body (the old section window's default size): the tab draws in a
/// child this big, and the Mini Remote (or the engine window hosting it) fits to it.
/// </summary>
public static Vector2 TabSize(IltSection section) => section switch
{
IltSection.Character => new Vector2(520, 440),
IltSection.Quests => new Vector2(700, 500),
IltSection.Pet => new Vector2(560, 580),
IltSection.Banking => new Vector2(560, 520),
IltSection.Gear => new Vector2(560, 520),
IltSection.Charms => new Vector2(560, 520),
IltSection.Games => new Vector2(520, 440),
_ => new Vector2(520, 440),
};
/// <summary>Draws one Mini Remote ILT tab's body into the current (child) window.</summary>
public void RenderTab(IltSection section)
{
if ((int)section != _lastTabLogged)
{
_lastTabLogged = (int)section;
RynthLog.Event(LogEvents.IltWindowShown, $"{IltSections.Label(section)} tab shown (world='{_ctx.Options.WorldName}', available={_hub.Available})");
}
switch (section)
{
case IltSection.Character: RenderCharacterBody(); break;
case IltSection.Quests: _hub.Quests.RenderTab(); break;
case IltSection.Pet: _hub.Pets.Render(); break;
case IltSection.Banking: _hub.Banking.Render(); break;
case IltSection.Gear: _hub.Gear.Render(); break;
case IltSection.Charms: _hub.CharmsTab.Render(); break;
case IltSection.Games: _hub.Games.Render(); break;
}
}
/// <summary>
/// The Guardian panel's body (RynthCore's ILT Guardian panel, RynthPluginRenderEmbed
/// "guardian"), or why it's idle while the server hasn't reported ILT features.
/// </summary>
public void RenderGuardianPanel()
{
if (!_hub.SectionAvailable(IltSection.Guardian))
{
RenderHeader();
ImGui.Separator();
RenderUnavailable();
return;
}
_hub.Guardian.Render();
}
/// <summary>Character tab: world / options header, then session rates (or why the ILT tabs are idle).</summary>
private void RenderCharacterBody()
{
RenderHeader();
ImGui.Separator();
if (!_hub.Available) { RenderUnavailable(); return; }
if (ImGui.CollapsingHeader("Session rates", ImGuiTreeNodeFlags.DefaultOpen)) _hub.Rates.Render();
ImGui.Spacing();
ImGui.TextDisabled("XP planner, Augmentations and Enlightenment are on the Skills panel's Progression tab");
ImGui.TextDisabled("(right-click the dashboard's Char button > Progression).");
}
private void RenderHeader()
{
var o = _ctx.Options;
string world = o.WorldName.Length > 0 ? o.WorldName : "unknown world";
ImGui.TextColored(o.IsIltLikeWorld ? LegacyDashboardRenderer.ColTeal : LegacyDashboardRenderer.ColTextMute, world);
ImGui.SameLine();
ImGui.TextDisabled(o.IsRefreshing ? "checking server options..."
: o.LastRefreshUtc == DateTime.MinValue ? "server options not checked yet"
: $"options via {o.Source} @ {o.LastRefreshUtc.ToLocalTime():t}");
ImGui.SameLine();
if (ImGui.SmallButton("Refresh##opts")) _ctx.Post(() => o.Refresh(manual: true));
bool force = _ctx.State.ForceLeaftideFeatures;
if (ImGui.Checkbox("Treat this world as ILT", ref force)) _ctx.State.ForceLeaftideFeatures = force;
if (ImGui.IsItemHovered())
ImGui.SetTooltip("World-identity override only: the Mini Remote asks the server which ILT features exist.\nIt never turns a feature on by itself.");
ImGui.SameLine();
if (ImGui.SmallButton("Profiles...")) { ImGui.OpenPopup("##iltprofiles"); _ctx.Post(() => _profileList = _ctx.Store.ListProfiles().ToArray()); }
RenderProfilesPopup();
}
private void RenderProfilesPopup()
{
if (!ImGui.BeginPopup("##iltprofiles")) return;
ImGui.TextColored(LegacyDashboardRenderer.ColTeal, "ILT profiles (settings only; no balances)");
ImGui.SetNextItemWidth(180);
ImGui.InputTextWithHint("##profname", "profile name", ref _profileName, 64u);
ImGui.SameLine();
ImGui.Checkbox("shared", ref _profileShared);
ImGui.SameLine();
if (ImGui.SmallButton("Save"))
{
string n = _profileName; bool sh = _profileShared;
_ctx.Post(() =>
{
_ctx.Chat(_ctx.Store.SaveProfile(_ctx.State, n, sh, out string err) ? $"[Mini Remote] Saved profile '{n}'." : "[Mini Remote] Save failed: " + err);
_profileList = _ctx.Store.ListProfiles().ToArray();
});
}
var list = _profileList;
if (list.Length > 0)
{
_profileIdx = Math.Clamp(_profileIdx, 0, list.Length - 1);
ImGui.SetNextItemWidth(180);
ImGui.Combo("##proflist", ref _profileIdx, list, list.Length);
ImGui.SameLine();
if (ImGui.SmallButton("Load"))
{
string n = list[_profileIdx];
_ctx.Confirm("Load ILT profile", $"Replace the current ILT settings with profile '{n}'?",
() => _ctx.Chat(_ctx.Store.LoadProfile(_ctx.State, n, out string err) ? $"[Mini Remote] Loaded profile '{n}'." : "[Mini Remote] Load failed: " + err),
"Load");
}
}
else ImGui.TextDisabled("No saved profiles.");
ImGui.EndPopup();
}
private void RenderUnavailable()
{
var o = _ctx.Options;
if (!o.IsIltLikeWorld)
{
ImGui.TextWrapped("This is not an Infinite Leaftide / ACECustom world, so the ILT tabs are idle. "
+ "If this shard runs ACECustom under another name, tick 'Treat this world as ILT' and press Refresh.");
}
else if (o.IsRefreshing || o.LastRefreshUtc == DateTime.MinValue)
{
ImGui.TextWrapped("Checking which ILT features this server has enabled...");
}
else
{
ImGui.TextWrapped("The server did not report any ILT features as enabled. Press Refresh to check again.");
}
}
// ── Confirmation modal ──────────────────────────────────────────────────
private void RenderConfirm()
{
if (_confirm == null)
{
if (!_ctx.TryTakeConfirm(out var next)) return;
_confirm = next;
_confirmOpened = false;
}
if (!_confirmOpened)
{
ImGui.OpenPopup(ConfirmPopupId);
_confirmOpened = true;
}
ImGui.SetNextWindowSize(new Vector2(420, 0), ImGuiCond.Appearing);
bool keepOpen = true;
if (ImGui.BeginPopupModal(ConfirmPopupId, ref keepOpen, ImGuiWindowFlags.AlwaysAutoResize))
{
ImGui.TextColored(LegacyDashboardRenderer.ColAmber, _confirm.Title);
ImGui.Separator();
ImGui.TextWrapped(_confirm.Message);
ImGui.Spacing();
if (ImGui.Button(_confirm.YesLabel + "##iltyes", new Vector2(120, 0)))
{
var act = _confirm.OnYes;
if (act != null) _ctx.Post(act);
_confirm = null;
ImGui.CloseCurrentPopup();
}
ImGui.SameLine();
if (ImGui.Button("Cancel##iltno", new Vector2(120, 0)))
{
_confirm = null;
ImGui.CloseCurrentPopup();
}
ImGui.EndPopup();
}
else
{
// Closed with the title-bar X (or never opened): treat as cancel.
_confirm = null;
}
if (!keepOpen) _confirm = null;
}
}

View file

@ -0,0 +1,315 @@
// IltInventory.cs — Shared item / player-property helper for every ILT Hub feature.
//
// One place for: WCID lookups (cached — the engine call is cheap but not free), stack
// counting, "is it equipped", appraisal requests (throttled), charm ON/OFF status from the
// appraisal Use text, and player int/bool/quad reads. Features never talk to the cache or
// the host for item facts directly, so behaviour (and its edge cases) stays consistent.
// Pump-thread only.
using System;
using System.Collections.Generic;
using System.Linq;
using RynthCore.Loot;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthAi.IltHub;
/// <summary>
/// Registered ACECustom charm (CharmAbilityRegistry): display name, every known WCID (base +
/// tier variants), the player PropertyBool the server sets while the ability is active (0 when
/// it is kept in memory only, like Auto-Rebuff) and a one-line effect summary.
/// </summary>
internal sealed record IltCharmDef(string Name, uint[] Wcids, uint PlayerFlag = 0, string Effect = "");
internal sealed class IltInventory
{
// ── Well-known WCIDs (ACECustom content) ────────────────────────────────
public const uint WcidPyreal = 273;
public const uint WcidEnlightenedCoin = 300004;
public const uint WcidEnlToken = 300000;
public const uint WcidEnlMedallion = 90000217;
public const uint WcidEnlSigil = 300101189;
public const uint WcidEnlCrest = 98769999;
public const uint WcidEncapsulatedSpirit = 49485;
public const uint WcidRuneOfDispel = 30133;
public const uint WcidSummonRefillCharm = 78780030;
public const uint WcidUniversalMasteryCharm = 78780031;
public static readonly uint[] WcidInfiniteCastingStone = { 777700019, 777700055 };
public const uint WcidRedAetheriaChunk = 42636;
public const uint WcidBlueAetheriaChunk = 42635;
// ── Property ids used by several features ───────────────────────────────
public const uint IntStackSize = 12;
public const uint IntValidLocations = 9;
public const uint IntLevel = 25;
public const uint IntMaxStructure = 91;
public const uint IntStructure = 92;
public const uint IntNumTimesTinkered = 171;
public const uint IntImbuedEffect = 179;
public const uint IntCleaving = 292;
public const uint IntItemMaxLevel = 319;
public const uint IntSummoningMastery = 362;
public const uint IntEnlightenment = 390;
public const uint IntSplitArrowCount = 9031;
public const uint IntMaterialType = 131;
public const uint IntUses = 92;
/// <summary>ACECustom charm item: current tier (PropertyInt.CharmLevel).</summary>
public const uint IntCharmLevel = 50005;
/// <summary>ACECustom charm item: highest tier for this charm line (PropertyInt.CharmMaxLevel).</summary>
public const uint IntCharmMaxLevel = 50006;
public const uint StrUse = 14;
public const uint QuadTotalXp = 1;
public const uint QuadAvailableXp = 2;
public const uint QuadItemTotalXp = 4;
/// <summary>ACECustom PropertyInt64.BankedLuminance (sent with each XP batch).</summary>
public const uint QuadBankedLuminance = 9005;
public const uint BoolNeverChunk = 9030;
public const uint BoolPyrealRefillActive = 9049;
public const uint BoolUniversalMasteryActive = 50038;
/// <summary>
/// Every charm in ACECustom's CharmAbilityRegistry (WCIDs and player flags match the server's
/// WCIDToAbilityId map and PropertyBool ids). Guardian Hand is not a registry charm and has no
/// published WCID — see IltGear.
/// </summary>
public static readonly IltCharmDef[] Charms =
{
new("Mana Barrier", new uint[] { 777700001, 777700054, 777710004, 777720004 }, 50010,
"Mana absorbs incoming damage (better ratio at higher tiers)."),
new("Infinite Casting", WcidInfiniteCastingStone, 50028,
"Infinite Casting Stone: spells cast without consuming components."),
new("Asheron's Favor", new uint[] { 777700020, 777710002, 777720002 }, 50030,
"+10 / 15 / 20% health and +50 / 100 / 250 natural armor."),
new("Artisan's", new uint[] { 777700021, 777710003, 777720003 }, 50031,
"Imbue success chance +4 / 8 / 12%."),
new("Shrapnel", new uint[] { 777700022 }, 50032,
"Tectonic Rifts cast as Rocky Shrapnel (Rocky Shrapnel must be learned)."),
new("Agony", new uint[] { 777700023 }, 50033,
"Tectonic Rifts I casts as Ring of Unspeakable Agony (the spell must be learned)."),
new("Split Cast", new uint[] { 777700024 }, 50035,
"Streak, Arc and Bolt spells split to several nearby targets."),
new("Explosive Arrow", new uint[] { 777700025, 777710005, 777720005 }, 50036,
"Arrow hits detonate an elemental ring at the target."),
new("Omni Strike", new uint[] { 777700026 }, 50037,
"Melee hits use the damage type the target is weakest to."),
new("Fork", new uint[] { 777700027, 777710007, 777720007 }, 50039,
"Streak, Arc and Bolt projectiles fork to nearby enemies (50 / 75 / 100% damage)."),
new("Auto-Rebuff", new uint[] { 777700300 }, 0,
"Keeps your buffs up automatically."),
new("Summon Essence Refill", new uint[] { WcidSummonRefillCharm }, BoolPyrealRefillActive,
"Refills an empty pet essence from banked pyreals when you summon."),
new("Universal Summoning Mastery", new uint[] { WcidUniversalMasteryCharm }, BoolUniversalMasteryActive,
"Use pet essences of any summoning mastery."),
};
private readonly RynthCoreHost _host;
private readonly Func<WorldObjectCache?> _cache;
private readonly Dictionary<int, uint> _wcidCache = new();
private readonly Dictionary<int, long> _lastIdRequest = new();
/// <summary>Don't re-request appraisal for the same object more often than this.</summary>
private const long IdRequestThrottleMs = 30_000;
public IltInventory(RynthCoreHost host, Func<WorldObjectCache?> cache)
{
_host = host;
_cache = cache;
}
public RynthCoreHost Host => _host;
public WorldObjectCache? Cache => _cache();
public uint PlayerId => _host.GetPlayerId();
// ── Player state ────────────────────────────────────────────────────────
/// <summary>The client busy hourglass is up (an action is in progress).</summary>
public bool IsBusy => _host.HasGetBusyState && _host.GetBusyState() != 0;
/// <summary>Player is in peace mode (combat mode NonCombat). True when the engine can't tell.</summary>
public bool InPeaceMode => !_host.HasGetCurrentCombatMode || _host.GetCurrentCombatMode() == CombatMode.NonCombat;
public int PlayerInt(uint stype, int fallback = 0)
=> _host.HasGetObjectIntProperty && _host.TryGetObjectIntProperty(PlayerId, stype, out int v) ? v : fallback;
public bool PlayerBool(uint stype)
=> _host.HasGetObjectBoolProperty && _host.TryGetObjectBoolProperty(PlayerId, stype, out bool v) && v;
public long PlayerQuad(uint stype)
=> _host.HasGetObjectQuadProperty && _host.TryGetObjectQuadProperty(PlayerId, stype, out long v) ? v : 0;
/// <summary>Current/max health from the engine vitals read (0/0 when unavailable).</summary>
public (uint Cur, uint Max) PlayerHealth()
{
if (_host.HasGetPlayerVitals && _host.TryGetPlayerVitals(out uint h, out uint mh, out _, out _, out _, out _))
return (h, mh);
return (0, 0);
}
// ── Item facts ──────────────────────────────────────────────────────────
/// <summary>All items the player carries or wears (snapshot).</summary>
public IEnumerable<WorldObject> Items() => _cache()?.GetInventory() ?? Enumerable.Empty<WorldObject>();
/// <summary>Weenie class id, cached per object (0 when unknown).</summary>
public uint Wcid(WorldObject wo)
{
if (_wcidCache.TryGetValue(wo.Id, out uint w) && w != 0) return w;
if (_host.HasGetObjectWcid && _host.TryGetObjectWcid(unchecked((uint)wo.Id), out w))
_wcidCache[wo.Id] = w;
return w;
}
public int Int(WorldObject wo, uint stype, int fallback = 0) => wo.Values(unchecked((int)stype), fallback);
public bool Bool(WorldObject wo, uint stype)
=> _host.HasGetObjectBoolProperty && _host.TryGetObjectBoolProperty(unchecked((uint)wo.Id), stype, out bool v) && v;
public long Quad(WorldObject wo, uint stype)
=> _host.HasGetObjectQuadProperty && _host.TryGetObjectQuadProperty(unchecked((uint)wo.Id), stype, out long v) ? v : 0;
public string Str(WorldObject wo, uint stype)
=> _host.HasGetObjectStringProperty && _host.TryGetObjectStringProperty(unchecked((uint)wo.Id), stype, out string v) ? v ?? string.Empty : string.Empty;
/// <summary>Stack size (1 for non-stackables).</summary>
public int StackSize(WorldObject wo) => Math.Max(1, Int(wo, IntStackSize, 1));
/// <summary>Remaining uses on a structure item (essences, kits, salvage bags).</summary>
public int Uses(WorldObject wo) => Int(wo, IntStructure, 0);
public bool IsEquipped(WorldObject wo)
=> wo.WieldedLocation > 0 || (wo.Wielder != 0 && unchecked((uint)wo.Wielder) == PlayerId);
public bool HasAppraisal(WorldObject wo)
=> !_host.HasHasAppraisalData || _host.HasAppraisalData(unchecked((uint)wo.Id));
/// <summary>Requests appraisal data, throttled per object. Returns true if a request was sent.</summary>
public bool RequestAppraisal(WorldObject wo)
{
if (!_host.HasRequestId) return false;
long now = Environment.TickCount64;
if (_lastIdRequest.TryGetValue(wo.Id, out long last) && now - last < IdRequestThrottleMs) return false;
_lastIdRequest[wo.Id] = now;
return _host.RequestId(unchecked((uint)wo.Id));
}
// ── Finders / counters ──────────────────────────────────────────────────
public WorldObject? FindByWcid(params uint[] wcids)
=> Items().FirstOrDefault(wo => Array.IndexOf(wcids, Wcid(wo)) >= 0);
public IEnumerable<WorldObject> AllByWcid(params uint[] wcids)
=> Items().Where(wo => Array.IndexOf(wcids, Wcid(wo)) >= 0);
public WorldObject? FindByName(Func<string, bool> predicate)
=> Items().FirstOrDefault(wo => predicate(wo.Name));
/// <summary>Total stack count of items with any of the given WCIDs.</summary>
public long CountByWcid(params uint[] wcids)
=> AllByWcid(wcids).Sum(wo => (long)StackSize(wo));
/// <summary>Total stack count of items whose name matches exactly (case-insensitive).</summary>
public long CountByName(string name)
=> Items().Where(wo => wo.Name.Equals(name, StringComparison.OrdinalIgnoreCase)).Sum(wo => (long)StackSize(wo));
/// <summary>Total stack count of a sigil-chain item (singular or plural stack name; see IltSigilChain.NameIs).</summary>
public long CountByChainName(string chainName)
=> Items().Where(wo => IltSigilChain.NameIs(wo.Name, chainName)).Sum(wo => (long)StackSize(wo));
/// <summary>
/// True when the player carries spell components or an Infinite Casting Stone that isn't
/// known to be switched OFF (an OFF stone doesn't waive components).
/// </summary>
public bool HasCastingSupplies()
=> AllByWcid(WcidInfiniteCastingStone).Any(stone => CharmStatus(stone) != IltTri.Off)
|| Items().Any(wo => wo.ObjectClass == AcObjectClass.SpellComponent);
/// <summary>Free main-pack slots (best effort: capacity minus direct children; -1 when unknown).</summary>
public int FreeMainPackSlots()
{
var cache = _cache();
if (cache == null) return -1;
int player = unchecked((int)PlayerId);
int capacity = PlayerInt((uint)LongValueKey.ItemsCapacity, 102);
int used = cache.GetDirectInventory()
.Count(wo => wo.Container == player && wo.WieldedLocation <= 0 && wo.ObjectClass != AcObjectClass.Container);
return Math.Max(0, capacity - used);
}
// ── Charms ──────────────────────────────────────────────────────────────
/// <summary>
/// ON/OFF/Unknown from the appraisal Use text ("... Status: ON"). Requests appraisal
/// (throttled) when the text isn't loaded yet.
/// </summary>
public IltTri CharmStatus(WorldObject charm)
{
string use = Str(charm, StrUse);
if (use.Length == 0)
{
RequestAppraisal(charm);
return IltTri.Unknown;
}
if (use.Contains("Status: ON", StringComparison.OrdinalIgnoreCase)) return IltTri.On;
if (use.Contains("Status: OFF", StringComparison.OrdinalIgnoreCase)) return IltTri.Off;
return IltTri.Unknown;
}
/// <summary>
/// Charm tier and max tier from the item's CharmLevel / CharmMaxLevel ints, else parsed from
/// the appraisal Use text ("Charm [Tier 2/3]"). (0, 0) until the appraisal is loaded.
/// </summary>
public (int Tier, int MaxTier) CharmTier(WorldObject charm)
{
int tier = Int(charm, IntCharmLevel, 0), max = Int(charm, IntCharmMaxLevel, 0);
if (tier > 0) return (tier, max);
var m = CharmTierText.Match(Str(charm, StrUse));
if (!m.Success) return (0, 0);
int.TryParse(m.Groups[1].Value, out tier);
if (m.Groups[2].Success) int.TryParse(m.Groups[2].Value, out max);
return (tier, max);
}
private static readonly System.Text.RegularExpressions.Regex CharmTierText =
new(@"Charm \[Tier (\d+)(?:/(\d+))?\]", System.Text.RegularExpressions.RegexOptions.CultureInvariant);
/// <summary>Charm definition for an item (by WCID), or null.</summary>
public IltCharmDef? CharmDefFor(WorldObject wo)
{
uint w = Wcid(wo);
if (w == 0) return null;
return Charms.FirstOrDefault(c => Array.IndexOf(c.Wcids, w) >= 0);
}
/// <summary>
/// Every charm the player carries: registered WCIDs plus anything whose Use text starts
/// with "Charm [Tier" (generic ACECustom charm format, catches charms added later).
/// </summary>
public List<WorldObject> CarriedCharms()
{
var list = new List<WorldObject>();
foreach (var wo in Items())
{
if (CharmDefFor(wo) != null) { list.Add(wo); continue; }
if (wo.ObjectClass is AcObjectClass.MeleeWeapon or AcObjectClass.MissileWeapon or AcObjectClass.Armor
or AcObjectClass.Clothing or AcObjectClass.Container or AcObjectClass.Corpse)
continue;
if (Str(wo, StrUse).StartsWith("Charm [Tier", StringComparison.OrdinalIgnoreCase)
|| wo.Name.EndsWith(" Charm", StringComparison.OrdinalIgnoreCase))
list.Add(wo);
}
return list;
}
// ── Actions ─────────────────────────────────────────────────────────────
public bool Use(WorldObject wo) => _host.HasUseObject && _host.UseObject(unchecked((uint)wo.Id));
public bool UseOn(WorldObject source, uint targetId)
=> _host.HasUseObjectOn && _host.UseObjectOn(unchecked((uint)source.Id), targetId);
/// <summary>Forgets cached WCIDs / appraisal throttles (logout).</summary>
public void Reset()
{
_wcidCache.Clear();
_lastIdRequest.Clear();
}
}

View file

@ -0,0 +1,109 @@
// IltParse.cs — Shared parsing / formatting helpers for ILT Hub server output.
//
// Centralised so every feature uses the same number parsing (commas, k/m/b/t suffixes),
// the same compact K/M/B display, and the same regexes. Regexes are static and built once;
// RegexOptions.Compiled is harmless under NativeAOT (it falls back to the interpreter).
using System;
using System.Globalization;
using System.Text.RegularExpressions;
namespace RynthCore.Plugin.RynthAi.IltHub;
internal static class IltParse
{
private const RegexOptions Opt = RegexOptions.Compiled | RegexOptions.CultureInvariant;
/// <summary>"/aug" level line: "Creature: 1,234".</summary>
public static readonly Regex AugLine = new(@"^(\w+):\s*([\d,]+)$", Opt);
/// <summary>"/pets" / "/shinies" roster entry: "12. Shiny Drudge Ravener".</summary>
public static readonly Regex RosterLine = new(@"^\s*(\d+)\.\s+(.+)$", Opt);
/// <summary>Bank-command amount entry: "1.5m", "250,000", "2b".</summary>
public static readonly Regex AmountInput = new(@"^([\d,.]+)\s*([kmbt]?)$", Opt | RegexOptions.IgnoreCase);
/// <summary>AC character name: starts with a letter, then letters, spaces, apostrophes or hyphens (max 32).</summary>
public static readonly Regex CharacterName = new(@"^[A-Za-z][A-Za-z '\-]{0,31}$", Opt);
/// <summary>A comma-grouped or plain integer as printed by ACE's N0 format.</summary>
public const string AmountPattern = @"(?:\d{1,3}(?:,\d{3})+|\d+)";
/// <summary>"Transferred 5,000 Pyreals to Bob" (optional " (offline)" / trailing "--- note").</summary>
public static readonly Regex BankSent = new(
@"^Transferred (" + AmountPattern + @") ([^']+?) to ([^-]+?)(?:\s*---.*)?$", Opt);
/// <summary>"Received 5,000 Pyreals from Bob".</summary>
public static readonly Regex BankReceived = new(
@"^Received (" + AmountPattern + @") ([^']+?) from (.+?)(?:\s*---.*)?$", Opt);
/// <summary>"/xp all" cost line: "[XP] Your XP cost for next 1 Strength level is: 1,234".</summary>
public static readonly Regex XpCost = new(@"\[XP\] Your XP cost for next 1 (\w+) level is: ([\d,]+)", Opt);
/// <summary>"/attr" success: "[ATTR] Strength attribute raised by 10, costing 1,234!".</summary>
public static readonly Regex AttrRaised = new(@"^\[ATTR\] (\w+) attribute raised by (\d+), costing ([\d,]+)", Opt);
/// <summary>Strips commas and parses the leading integer; 0 when absent.</summary>
public static long ParseLeadingLong(string text)
{
if (string.IsNullOrEmpty(text)) return 0;
string s = text.Replace(",", string.Empty).Trim();
int end = 0;
while (end < s.Length && char.IsDigit(s[end])) end++;
return end > 0 && long.TryParse(s.AsSpan(0, end), NumberStyles.None, CultureInfo.InvariantCulture, out long v) ? v : 0;
}
/// <summary>
/// Parses a user-entered amount with optional k/m/b/t suffix ("1.5m" → 1,500,000).
/// Returns false for empty, negative, or overflowing input.
/// </summary>
public static bool TryParseAmount(string input, out long amount)
{
amount = 0;
var m = AmountInput.Match((input ?? string.Empty).Trim());
if (!m.Success) return false;
if (!decimal.TryParse(m.Groups[1].Value.Replace(",", string.Empty), NumberStyles.AllowDecimalPoint,
CultureInfo.InvariantCulture, out decimal baseVal))
return false;
decimal mult = char.ToLowerInvariant(m.Groups[2].Value.Length > 0 ? m.Groups[2].Value[0] : ' ') switch
{
'k' => 1_000m,
'm' => 1_000_000m,
'b' => 1_000_000_000m,
't' => 1_000_000_000_000m,
_ => 1m,
};
decimal total = Math.Floor(baseVal * mult);
if (total <= 0 || total > long.MaxValue) return false;
amount = (long)total;
return true;
}
/// <summary>Compact display: 950 → "950", 12_300 → "12.3K", 4_500_000 → "4.50M", 2e9 → "2.00B".</summary>
public static string Compact(double value)
{
double a = Math.Abs(value);
string s = a >= 1e12 ? (value / 1e12).ToString("0.00", CultureInfo.InvariantCulture) + "T"
: a >= 1e9 ? (value / 1e9).ToString("0.00", CultureInfo.InvariantCulture) + "B"
: a >= 1e6 ? (value / 1e6).ToString("0.00", CultureInfo.InvariantCulture) + "M"
: a >= 1e3 ? (value / 1e3).ToString("0.0", CultureInfo.InvariantCulture) + "K"
: value.ToString("0", CultureInfo.InvariantCulture);
return s;
}
/// <summary>Full grouped display: 1234567 → "1,234,567".</summary>
public static string N0(long value) => value.ToString("N0", CultureInfo.InvariantCulture);
/// <summary>"3d 4h 12m 5s" style duration; "ready" when zero or negative.</summary>
public static string Duration(TimeSpan span)
{
if (span <= TimeSpan.Zero) return "ready";
if (span.TotalDays >= 1) return $"{(int)span.TotalDays}d {span.Hours}h {span.Minutes}m";
if (span.TotalHours >= 1) return $"{span.Hours}h {span.Minutes}m {span.Seconds}s";
if (span.TotalMinutes >= 1) return $"{span.Minutes}m {span.Seconds}s";
return $"{span.Seconds}s";
}
/// <summary>Strips "&lt;Tell:…&gt;" style markup the chat window sometimes leaves on names.</summary>
public static string StripMarkup(string text)
=> Regex.Replace(text ?? string.Empty, @"<[^>]*>", string.Empty).Trim();
}

View file

@ -0,0 +1,323 @@
// IltPetStats.cs — Mag-Tools / UtilityBelt-style stats for one carried pet essence.
//
// Line 1: Name, Bond N, Lvl N, Craft N
// Line 2: Sex, Growth, Mut N, Potency S (A act +P%), Mastery, DamageType
// Line 3: [D, DR, C, CD, CR, CDR] Uses cur/max Breed Ready|n/m|Rec 4h|Juv|Neut
//
// Property ids are ACECustom (ILT) pet-device qualities, the same ones UtilityBelt's Pets
// tab reads (UB Lib\IltPetAceConstants.cs). Bond, level, craft and ratings are appraisal
// data: they read 0 until the essence has been ID'd, which HasId reports.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthAi.IltHub;
/// <summary>Pet summon category (UB Pets "Type"). Persisted as int in <see cref="IltPetAssignment.Kind"/>.</summary>
internal enum IltPetKind { Combat = 0, Healing = 1, Cosmetic = 2 }
/// <summary>Roster sort modes (persisted as int in <see cref="IltPetState.RosterSort"/>).</summary>
internal enum IltPetSort { Priority = 0, Bond = 1, Potency = 2, BreedReady = 3, Level = 4, Uses = 5, Name = 6 }
/// <summary>One carried essence with its decoded stats. Built on the pump thread, read by the UI.</summary>
internal sealed class IltPetStats
{
public int Id;
public string Name = string.Empty;
public uint Wcid;
public IltPetKind Kind;
/// <summary>Kind came from a user assignment rather than auto-detection.</summary>
public bool KindAssigned;
public bool HasId;
public int Bond;
public int Level;
public int Craft;
public string Sex = "?";
public string Growth = string.Empty;
public int Mutations;
public int StoredPotency;
public int ActivePotency;
public int DamageBonusPercent;
public string Mastery = string.Empty;
public string DamageType = string.Empty;
public int D, DR, C, CD, CR, CDR;
public int UsesCur;
public int UsesMax;
public string Breed = "-";
public bool BreedReady;
/// <summary>Chosen for its kind: in the combat summon list, the heal pet, or the cosmetic pet.</summary>
public bool Selected;
/// <summary>Combat summon priority (list index), or int.MaxValue when not in the list.</summary>
public int Priority = int.MaxValue;
public string Line1 = string.Empty;
public string Line2 = string.Empty;
public string Line3 = string.Empty;
}
/// <summary>Reads and formats <see cref="IltPetStats"/>. Pump thread only (host reads).</summary>
internal static class IltPetStatsReader
{
// ── ACECustom / ACE property ids (UB IltPetAceConstants, PetEssenceItemInfoFormatter) ──
private const uint IntDamageType = 45;
private const uint IntMaxStructure = 91;
private const uint IntStructure = 92;
private const uint IntWorkmanship = 105;
private const uint IntSummoningMastery = 362;
private const uint IntUseLevelRequirement = 364;
private const uint IntUseRequiresLevel = 369;
private const uint IntGearDamage = 370;
private const uint IntGearDamageResist = 371;
private const uint IntGearCrit = 372;
private const uint IntGearCritResist = 373;
private const uint IntGearCritDamage = 374;
private const uint IntGearCritDamageResist = 375;
private const uint IntDamageRating = 307;
private const uint IntDamageResistRating = 308;
private const uint IntCritRating = 313;
private const uint IntCritDamageRating = 314;
private const uint IntCritResistRating = 315;
private const uint IntCritDamageResistRating = 316;
private const uint IntBondLevel = 9053;
private const uint IntCapturedDamageType = 9054;
private const uint IntPotencyStored = 9056;
private const uint IntMaleBreedingCharges = 9057;
private const uint IntMutDamage = 9070;
private const uint IntMutDamageResist = 9071;
private const uint IntMutCrit = 9072;
private const uint IntMutVitality = 9073;
private const uint IntMutPotency = 9074;
private const uint IntMutationCount = 9075;
private const uint IntMaturityKills = 9077;
private const uint FloatNextBreedingTime = 9056;
private const uint BoolNeutered = 9051;
private const uint BoolMaleOverride = 50053;
private const uint BoolJuvenile = 50054;
// ACE PetPotencyMath defaults (UB PetEssencePotencyMath).
private const int PotencyActiveCap = 150;
private const int PotencyBondDivisor = 10;
private const double PotencyDamagePerLevelPercent = 2.0;
/// <summary>ACE pet_breeding_male_max_charges default.</summary>
private const int MaleMaxBreedingCharges = 10;
/// <summary>Decodes every stat for <paramref name="wo"/> and fills the three display lines.</summary>
public static IltPetStats Read(RynthCoreHost host, IltInventory inv, WorldObject wo, long unixNow)
{
uint id = unchecked((uint)wo.Id);
var s = new IltPetStats
{
Id = wo.Id,
Name = wo.Name,
Wcid = inv.Wcid(wo),
HasId = inv.HasAppraisal(wo),
UsesCur = inv.Int(wo, IntStructure),
UsesMax = inv.Int(wo, IntMaxStructure),
};
s.Bond = inv.Int(wo, IntBondLevel);
s.Level = inv.Int(wo, IntUseRequiresLevel);
if (s.Level <= 0) s.Level = inv.Int(wo, IntUseLevelRequirement);
s.Craft = inv.Int(wo, IntWorkmanship);
// Sex: explicit override when the server set one, else ACE PetDevice.IsMale's GUID hash.
bool isMale = TryBool(host, id, BoolMaleOverride, out bool male) ? male : DeriveIsMale(wo.Id);
bool neutered = TryBool(host, id, BoolNeutered, out bool n) && n;
bool juvenile = TryBool(host, id, BoolJuvenile, out bool j) && j;
s.Sex = (isMale ? "M" : "F") + (neutered ? "n" : juvenile ? "j" : string.Empty);
// Growth only exists on bred essences (9077 present, even when 0).
if (TryInt(host, id, IntMaturityKills, out int kills))
s.Growth = !juvenile ? "Adult" : kills > 0 ? "Juv " + kills.ToString(CultureInfo.InvariantCulture) : "Juv";
int total = inv.Int(wo, IntMutationCount);
s.Mutations = total > 0 ? total
: inv.Int(wo, IntMutDamage) + inv.Int(wo, IntMutDamageResist) + inv.Int(wo, IntMutCrit)
+ inv.Int(wo, IntMutVitality) + inv.Int(wo, IntMutPotency);
s.StoredPotency = Math.Max(0, inv.Int(wo, IntPotencyStored));
s.ActivePotency = ActivePotency(s.StoredPotency, s.Bond);
s.DamageBonusPercent = (int)Math.Round(s.ActivePotency * PotencyDamagePerLevelPercent);
s.Mastery = inv.Int(wo, IntSummoningMastery) switch
{
1 => "Primalist",
2 => "Necromancer",
3 => "Naturalist",
_ => string.Empty,
};
int dmg = inv.Int(wo, IntCapturedDamageType);
if (dmg <= 0) dmg = inv.Int(wo, IntDamageType);
s.DamageType = DamageTypeName(dmg);
// Gear ratings first (what Mag ItemInfo shows), else the base rating ids.
s.D = inv.Int(wo, IntGearDamage);
s.DR = inv.Int(wo, IntGearDamageResist);
s.C = inv.Int(wo, IntGearCrit);
s.CR = inv.Int(wo, IntGearCritResist);
s.CD = inv.Int(wo, IntGearCritDamage);
s.CDR = inv.Int(wo, IntGearCritDamageResist);
if (s.D <= 0 && s.DR <= 0 && s.C <= 0 && s.CR <= 0 && s.CD <= 0 && s.CDR <= 0)
{
s.D = inv.Int(wo, IntDamageRating);
s.DR = inv.Int(wo, IntDamageResistRating);
s.C = inv.Int(wo, IntCritRating);
s.CD = inv.Int(wo, IntCritDamageRating);
s.CR = inv.Int(wo, IntCritResistRating);
s.CDR = inv.Int(wo, IntCritDamageResistRating);
}
int charges = inv.Int(wo, IntMaleBreedingCharges);
double nextBreed = TryDouble(host, id, FloatNextBreedingTime, out double nb) ? nb : 0;
(s.Breed, s.BreedReady) = FormatBreed(isMale, neutered, juvenile, charges, nextBreed, unixNow);
FormatLines(s);
return s;
}
/// <summary>Builds Line1..Line3 from the decoded fields (Kind/Selected don't affect the text).</summary>
public static void FormatLines(IltPetStats s)
{
var l1 = new StringBuilder(s.Name);
if (s.Bond > 0) l1.Append(", Bond ").Append(s.Bond.ToString(CultureInfo.InvariantCulture));
if (s.Level > 0) l1.Append(", Lvl ").Append(s.Level.ToString(CultureInfo.InvariantCulture));
if (s.Craft > 0) l1.Append(", Craft ").Append(s.Craft.ToString(CultureInfo.InvariantCulture));
s.Line1 = l1.ToString();
var l2 = new StringBuilder(s.Sex);
if (s.Growth.Length > 0) l2.Append(", Growth ").Append(s.Growth);
l2.Append(", Mut ").Append(s.Mutations.ToString(CultureInfo.InvariantCulture));
l2.Append(", Potency ").Append(s.StoredPotency.ToString(CultureInfo.InvariantCulture));
if (s.StoredPotency > 0)
l2.Append(" (").Append(s.ActivePotency.ToString(CultureInfo.InvariantCulture))
.Append(" act +").Append(s.DamageBonusPercent.ToString(CultureInfo.InvariantCulture)).Append("%)");
if (s.Mastery.Length > 0) l2.Append(", ").Append(s.Mastery);
if (s.DamageType.Length > 0) l2.Append(", ").Append(s.DamageType);
s.Line2 = l2.ToString();
var parts = new List<string>(4);
string ratings = RatingsBracket(s);
if (ratings.Length > 0) parts.Add(ratings);
if (s.UsesMax > 0) parts.Add($"Uses {s.UsesCur}/{s.UsesMax}");
else if (s.UsesCur > 0) parts.Add($"Uses {s.UsesCur}");
if (s.Breed != "-") parts.Add("Breed " + s.Breed);
if (!s.HasId) parts.Add("ID pending");
s.Line3 = parts.Count > 0 ? string.Join(" ", parts) : "-";
}
/// <summary>Orders rows for display; ties keep a stable name order.</summary>
public static IltPetStats[] Sort(IEnumerable<IltPetStats> rows, IltPetSort mode)
{
var list = new List<IltPetStats>(rows);
Comparison<IltPetStats> byName = (a, b) => string.Compare(a.Name, b.Name, StringComparison.OrdinalIgnoreCase);
Comparison<IltPetStats> cmp = mode switch
{
// Selected first, then combat priority, then name.
IltPetSort.Priority => (a, b) => Chain(b.Selected.CompareTo(a.Selected), a.Priority.CompareTo(b.Priority), byName(a, b)),
IltPetSort.Bond => (a, b) => Chain(b.Bond.CompareTo(a.Bond), byName(a, b)),
IltPetSort.Potency => (a, b) => Chain(b.StoredPotency.CompareTo(a.StoredPotency), b.ActivePotency.CompareTo(a.ActivePotency), byName(a, b)),
IltPetSort.BreedReady => (a, b) => Chain(b.BreedReady.CompareTo(a.BreedReady), b.Bond.CompareTo(a.Bond), byName(a, b)),
IltPetSort.Level => (a, b) => Chain(b.Level.CompareTo(a.Level), byName(a, b)),
IltPetSort.Uses => (a, b) => Chain(b.UsesCur.CompareTo(a.UsesCur), byName(a, b)),
_ => byName,
};
list.Sort(cmp);
return list.ToArray();
}
private static int Chain(params int[] results)
{
foreach (int r in results) if (r != 0) return r;
return 0;
}
/// <summary>ACE PetPotencyMath: min(stored, ceil(bond / 10)), at least 1 with any bond, capped at 150.</summary>
private static int ActivePotency(int stored, int bond)
{
if (stored <= 0 || bond <= 0) return 0;
int cap = Math.Max(1, (bond + PotencyBondDivisor - 1) / PotencyBondDivisor);
return Math.Min(stored, Math.Min(cap, PotencyActiveCap));
}
/// <summary>ACE PetDevice.IsMale when no override is set (murmur3 fmix32 on the object GUID).</summary>
private static bool DeriveIsMale(int objectId)
{
uint h = unchecked((uint)objectId);
h ^= h >> 16;
h = unchecked(h * 0x7feb352d);
h ^= h >> 15;
h = unchecked(h * 0x846ca68b);
h ^= h >> 16;
return (h & 1) == 0;
}
/// <summary>Breeding cell: Neut / Juv / male charges n/max / female "Rec Nh" or "Ready".</summary>
private static (string Text, bool Ready) FormatBreed(bool isMale, bool neutered, bool juvenile,
int maleCharges, double nextBreedingUnix, long unixNow)
{
if (neutered) return ("Neut", false);
if (juvenile) return ("Juv", false);
if (isMale)
{
int ch = Math.Max(0, maleCharges);
return ($"{ch}/{MaleMaxBreedingCharges}", ch > 0);
}
if (nextBreedingUnix > 0 && unixNow < (long)nextBreedingUnix)
{
long remain = (long)nextBreedingUnix - unixNow;
int hours = (int)(remain / 3600);
return (hours > 0 ? $"Rec {hours}h" : $"Rec {(int)(remain % 3600 / 60)}m", false);
}
return ("Ready", true);
}
private static string RatingsBracket(IltPetStats s)
{
var sb = new StringBuilder();
void Add(string label, int v)
{
if (v <= 0) return;
if (sb.Length > 0) sb.Append(", ");
sb.Append(label).Append(' ').Append(v.ToString(CultureInfo.InvariantCulture));
}
Add("D", s.D); Add("DR", s.DR); Add("C", s.C); Add("CD", s.CD); Add("CR", s.CR); Add("CDR", s.CDR);
return sb.Length > 0 ? "[" + sb + "]" : string.Empty;
}
/// <summary>Single AC DamageType flag → name (combined flags return empty).</summary>
private static string DamageTypeName(int flags) => flags switch
{
1 => "Slash",
2 => "Pierce",
4 => "Bludgeon",
8 => "Cold",
16 => "Fire",
32 => "Acid",
64 => "Lightning",
1024 => "Nether",
_ => string.Empty,
};
private static bool TryBool(RynthCoreHost host, uint id, uint stype, out bool v)
{
v = false;
return host.HasGetObjectBoolProperty && host.TryGetObjectBoolProperty(id, stype, out v);
}
private static bool TryInt(RynthCoreHost host, uint id, uint stype, out int v)
{
v = 0;
return host.HasGetObjectIntProperty && host.TryGetObjectIntProperty(id, stype, out v);
}
private static bool TryDouble(RynthCoreHost host, uint id, uint stype, out double v)
{
v = 0;
return host.HasGetObjectDoubleProperty && host.TryGetObjectDoubleProperty(id, stype, out v);
}
}

View file

@ -0,0 +1,982 @@
// IltPets.cs — ILT Hub "Pet" tab.
//
// * Pet roster (UtilityBelt Pets-tab style): every carried pet essence with three stat
// lines (bond / level / craft · sex / mutations / potency / mastery · ratings / uses /
// breeding), filtered by summon type (Combat / Healing / Cosmetic) and sortable.
// Pets are detected by type (essence WCID block, summoning-gem icon underlay,
// Summoning use requirement, ACECustom bond/potency) — a pet-like name only nominates
// an item for appraisal. Healing Buddy / Dule box and cosmetic naming pick the type,
// else Combat; any essence can be re-typed ("Add sel." or right-click a row).
// - Combat: the tick list is the existing ConsumableRules Type=="Pet" list that
// PetManager summons from (list order = summon priority) — no second summoner.
// - Healing: the tick picks the heal pet the healing state machine uses.
// - Cosmetic: the tick picks a display pet; "Keep cosmetic pet out" summons it in
// peace mode and dismisses it when PetManager needs the slot for a fight.
// Summon / Despawn act on the highlighted row (or the type's chosen pet).
// * Pet charms: Summon Essence Refill (server refills an empty essence from banked
// pyreals) and Universal Summoning Mastery, read from the charm appraisal text and the
// player bools the server stamps. Feeds PetManager.AllowSummonOnEmpty.
// * Healing pet (UB HealingBuddy subset): summons a heal pet when HP drops, dismisses it
// after the heal lands, holds PetManager's combat summons while it is out.
// * /pets and /shinies roster capture (read-only display).
using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
using ImGuiNET;
using RynthCore.Plugin.RynthAi.LegacyUi;
namespace RynthCore.Plugin.RynthAi.IltHub;
internal sealed class IltPets : IIltFeature
{
private static readonly string[] KindNames = { "Combat", "Healing", "Cosmetic" };
private static readonly string[] SortNames = { "Priority", "Bond", "Potency", "Breed ready", "Level", "Uses", "Name" };
/// <summary>Un-ID'd essences auto-appraised per 2 s scan (keeps the server request rate low).</summary>
private const int AutoAppraisePerScan = 2;
private readonly IltHubContext _ctx;
// Healing-pet state machine.
private enum HealState { Idle, Summoning, Despawning }
private HealState _heal = HealState.Idle;
private long _healStartedAt;
private long _despawnAt;
private long _healCooldownUntil;
private int _healEssenceId;
private long _lastHealThink;
private string _healStatus = "idle";
// Roster snapshot (rebuilt on the pump thread, read by the render thread).
private volatile IltPetStats[] _pets = Array.Empty<IltPetStats>();
private long _lastPetScan;
// Active-pet / cosmetic bookkeeping (pump thread; the ui* copies are for the render thread).
private long _lastPresenceThink;
private int _lastSummonEssenceId;
private int _cosmeticOutEssenceId;
private long _cosmeticNextAt;
private volatile string _uiActivePet = string.Empty;
private volatile string _cosmeticStatus = "off";
private volatile string _hudPetName = string.Empty;
private volatile string _hudPetStatus = string.Empty;
/// <summary>Mini Remote pet line: the pet that is out, else the first combat essence in priority order.</summary>
public string HudPetName => _hudPetName;
/// <summary>Mini Remote pet status: "Out", "Ready", "Empty" or "Healing" (empty when there is no pet).</summary>
public string HudPetStatus => _hudPetStatus;
// Charm / supply status cached for the render thread.
private volatile bool _uiRefillActive;
private volatile bool _uiMasteryActive;
private volatile bool _uiHasCasting = true;
// Render-thread only: highlighted row and the sorted view cache.
private int _highlightId;
private IltPetStats[]? _viewSource;
private int _viewKind = -1;
private int _viewSort = -1;
private IltPetStats[] _view = Array.Empty<IltPetStats>();
public IltPets(IltHubContext ctx) => _ctx = ctx;
private IltPetState S => _ctx.State.Pet;
// ── Classification ──────────────────────────────────────────────────────
// Pet-device type signals (client-visible assessment properties).
private const uint IntMaxStructure = 91;
private const uint IntUseRequiresSkill = 366;
private const uint IntUseRequiresSkillSpec = 368;
private const uint IntBondLevel = 9053; // ACECustom pet essence
private const uint IntPotencyStored = 9056; // ACECustom pet essence
private const int SkillSummoning = 54;
private const uint DidIconUnderlay = 52;
/// <summary>Low 24 bits of the summoning-gem icon underlay (0x06007420) every pet device carries.</summary>
private const uint SummonGemUnderlay = 0x007420;
/// <summary>Icon-underlay verdict per object id (the DID never changes; only successful reads are cached).</summary>
private readonly Dictionary<int, bool> _underlayCache = new();
/// <summary>
/// True when the item is a pet device by type, not by name: the ACECustom combat
/// essence WCID block, the summoning-gem icon underlay, a Summoning-skill use
/// requirement, or ACECustom bond/potency properties. Names (" Essence", heal /
/// stamina / cosmetic pet naming) only make an item a candidate, which must then show
/// charges (MaxStructure) — so augmentation gems like "Jibril's Essence" stay out.
/// Spirits, charms, capture devices and summoned pet creatures are never pets.
/// </summary>
public bool IsPetDevice(WorldObject wo)
{
uint w = _ctx.Inventory.Wcid(wo);
if (w == IltInventory.WcidEncapsulatedSpirit) return false;
if (w is >= 78780030 and <= 78780089) return false; // charm block
if (w is >= 78780001 and <= 78780012) return false; // capture devices
if (w is >= 787802001 and <= 787802072) return false; // summoned combat pet creatures
if (w is >= 787801001 and <= 787801072) return true; // combat essence block
if (HasSummonGemUnderlay(wo)) return true;
if (RequiresSummoning(wo)) return true;
if (_ctx.Inventory.Int(wo, IntBondLevel) > 0 || _ctx.Inventory.Int(wo, IntPotencyStored, -1) >= 0) return true;
return IsPetNameCandidate(wo.Name) && _ctx.Inventory.Int(wo, IntMaxStructure) > 0;
}
/// <summary>Name hints UB's pet scan uses; never sufficient on their own (see <see cref="IsPetDevice"/>).</summary>
private static bool IsPetNameCandidate(string n)
=> n.EndsWith(" Essence", StringComparison.OrdinalIgnoreCase)
|| LooksLikeHealPet(n) || LooksLikeStaminaPet(n) || LooksLikeCosmeticPet(n);
/// <summary>UseRequiresSkill / UseRequiresSkillSpec is Summoning (appraisal data).</summary>
private bool RequiresSummoning(WorldObject wo)
=> _ctx.Inventory.Int(wo, IntUseRequiresSkill) == SkillSummoning
|| _ctx.Inventory.Int(wo, IntUseRequiresSkillSpec) == SkillSummoning;
/// <summary>Icon underlay is the summoning gem (network-populated, no appraisal needed; engine 2026.10.4.19+).</summary>
private bool HasSummonGemUnderlay(WorldObject wo)
{
if (_underlayCache.TryGetValue(wo.Id, out bool known)) return known;
var host = _ctx.Host;
if (!host.HasGetObjectDataIdProperty
|| !host.TryGetObjectDataIdProperty(unchecked((uint)wo.Id), DidIconUnderlay, out uint did))
return false;
bool match = (did & 0x00FFFFFF) == SummonGemUnderlay;
_underlayCache[wo.Id] = match;
return match;
}
/// <summary>"Healing Buddy" / "Dule box" naming used by the server's heal pets.</summary>
private static bool LooksLikeHealPet(string n)
=> (n.Contains("healing", StringComparison.OrdinalIgnoreCase) && n.Contains("buddy", StringComparison.OrdinalIgnoreCase))
|| (n.Contains("dule", StringComparison.OrdinalIgnoreCase) && n.Contains("box", StringComparison.OrdinalIgnoreCase));
/// <summary>Stamina buddy / crate / pet naming.</summary>
private static bool LooksLikeStaminaPet(string n)
=> n.Contains("stamina", StringComparison.OrdinalIgnoreCase)
&& (n.Contains("buddy", StringComparison.OrdinalIgnoreCase) || n.Contains("crate", StringComparison.OrdinalIgnoreCase)
|| n.Contains("pet", StringComparison.OrdinalIgnoreCase));
/// <summary>Cosmetic / plush / display pet naming.</summary>
private static bool LooksLikeCosmeticPet(string n)
=> n.Contains("cosmetic", StringComparison.OrdinalIgnoreCase) || n.Contains("plush", StringComparison.OrdinalIgnoreCase)
|| n.Contains("display pet", StringComparison.OrdinalIgnoreCase);
/// <summary>Name candidate that hasn't been appraised yet, so its type can't be confirmed.</summary>
private bool IsUnconfirmedCandidate(WorldObject wo)
=> IsPetNameCandidate(wo.Name) && !IsPetDevice(wo)
&& _ctx.Host.HasHasAppraisalData && !_ctx.Inventory.HasAppraisal(wo);
private IltPetAssignment? FindAssignment(string name)
=> S.Assignments.FirstOrDefault(a => a.Name.Equals(name, StringComparison.OrdinalIgnoreCase));
/// <summary>
/// Summon type for a carried item: the user's override wins, then the configured heal
/// pet. Anything else must be a pet device by type (<see cref="IsPetDevice"/>); its
/// naming then picks Healing / Cosmetic, defaulting to Combat. Null = not a pet.
/// </summary>
private IltPetKind? ClassifyKind(WorldObject wo, out bool assigned)
{
var a = FindAssignment(wo.Name);
if (a != null)
{
assigned = true;
return (IltPetKind)Math.Clamp(a.Kind, 0, 2);
}
assigned = false;
if (NameIs(wo, S.HealPetName)) return IltPetKind.Healing;
if (!IsPetDevice(wo)) return null;
if (LooksLikeHealPet(wo.Name)) return IltPetKind.Healing;
if (LooksLikeCosmeticPet(wo.Name)) return IltPetKind.Cosmetic;
return IltPetKind.Combat;
}
private static bool NameIs(WorldObject wo, string name)
=> !string.IsNullOrWhiteSpace(name) && wo.Name.Equals(name.Trim(), StringComparison.OrdinalIgnoreCase);
private WorldObject? FindCarried(string name)
=> string.IsNullOrWhiteSpace(name) ? null : _ctx.Inventory.Items().FirstOrDefault(wo => NameIs(wo, name));
/// <summary>Heal-pet essence: the ticked heal pet, else the first Healing-typed essence.</summary>
private WorldObject? FindHealEssence()
{
if (!string.IsNullOrWhiteSpace(S.HealPetName)) return FindCarried(S.HealPetName);
return _ctx.Inventory.Items().FirstOrDefault(wo => ClassifyKind(wo, out _) == IltPetKind.Healing);
}
// ── Charms / gates ──────────────────────────────────────────────────────
/// <summary>Summon Essence Refill charm is carried and switched on (or the server stamped the player bool).</summary>
public bool RefillCharmActive()
{
if (_ctx.Inventory.PlayerBool(IltInventory.BoolPyrealRefillActive)) return true;
var charm = _ctx.Inventory.FindByWcid(IltInventory.WcidSummonRefillCharm);
return charm != null && _ctx.Inventory.CharmStatus(charm) == IltTri.On;
}
public bool MasteryCharmActive()
{
if (_ctx.Options.IsOff(IltFeature.UniversalMastery)) return false;
if (_ctx.Inventory.PlayerBool(IltInventory.BoolUniversalMasteryActive)) return true;
var charm = _ctx.Inventory.FindByWcid(IltInventory.WcidUniversalMasteryCharm);
return charm != null && _ctx.Inventory.CharmStatus(charm) == IltTri.On;
}
/// <summary>
/// PetManager hook: summon from an empty essence (spends banked pyreals) only when the
/// player opted in, the refill charm is active, and the server has positively confirmed
/// the feature: either /ilt features reported pet_refill on, or the server stamped the
/// player's refill bool. An unknown feature state never spends.
/// </summary>
public bool AllowSummonOnEmpty()
{
if (!S.UsePyrealRefillPath || !_ctx.Options.IsIltLikeWorld || !RefillCharmActive()) return false;
bool confirmed = _ctx.Options.IsOn(IltFeature.PetRefill)
|| _ctx.Inventory.PlayerBool(IltInventory.BoolPyrealRefillActive);
if (!confirmed) RynthLog.Trace(LogCat.IltPets, "summon-on-empty refused: pet_refill not confirmed by the server");
return confirmed;
}
/// <summary>PetManager hook: hold combat summons while the heal pet cycle is running.</summary>
public bool HoldCombatSummons() => _heal != HealState.Idle;
/// <summary>
/// PetManager hook (pump thread): a pet already holds the slot and monsters are near.
/// When that pet is the cosmetic pet, dismiss it so a combat pet can be summoned.
/// Returns true when a dismiss was issued.
/// </summary>
public bool YieldPetForCombat()
{
if (_heal != HealState.Idle || string.IsNullOrWhiteSpace(S.CosmeticPetName)) return false;
var pet = FindOwnPet();
var essence = FindCarried(S.CosmeticPetName);
if (pet == null || essence == null) return false;
if (!PetMatchesEssence(pet, essence) && _cosmeticOutEssenceId != essence.Id) return false;
if (_ctx.Inventory.IsBusy || !_ctx.Inventory.Use(essence)) return false;
long now = IltHubContext.NowMs;
_cosmeticOutEssenceId = 0;
_cosmeticNextAt = now + Math.Max(5, S.CosmeticRespawnSeconds) * 1000L;
_cosmeticStatus = "dismissed for combat";
RynthLog.Trace(LogCat.IltPets, $"cosmetic pet '{pet.Name}' dismissed so a combat pet can be summoned");
return true;
}
// ── Rosters ─────────────────────────────────────────────────────────────
/// <summary>Captures /pets or /shinies into the state (quiet).</summary>
public void RequestRoster(bool shinies)
{
RynthLog.Trace(LogCat.IltPets, $"RequestRoster(shinies={shinies})");
string cmd = shinies ? "/shinies" : "/pets";
if (_ctx.Capture.IsPending(cmd)) return;
string header = shinies ? "Your Shiny Log" : "Your Pet Log";
_ctx.Capture.Enqueue(new IltChatRequest
{
Command = cmd,
IsResponseLine = t => t.Contains(header, StringComparison.OrdinalIgnoreCase) || IltParse.RosterLine.IsMatch(t),
IsTerminator = t => t.Contains(header + " is empty", StringComparison.OrdinalIgnoreCase),
IdleEndMs = 1500,
FirstLineTimeoutMs = 10000,
Eat = true,
OnComplete = r =>
{
if (r.UnknownCommand) { _ctx.Options.Set(shinies ? IltFeature.Shinies : IltFeature.Pets, IltTri.Off); return; }
if (r.Lines.Count == 0) return;
_ctx.Options.Set(shinies ? IltFeature.Shinies : IltFeature.Pets, IltTri.On);
ApplyRoster(shinies, r.Lines);
},
});
}
/// <summary>Also used by the login probe tap so the roster fills without a second command.</summary>
public void ApplyRoster(bool shinies, List<string> lines)
{
RynthLog.Trace(LogCat.IltPets, $"ApplyRoster(shinies={shinies}, lines={lines.Count})");
var list = new List<string>();
foreach (string l in lines)
{
var m = IltParse.RosterLine.Match(l);
if (m.Success) list.Add(m.Groups[2].Value.Trim());
}
if (shinies) S.ShinyLog = list; else S.PetLog = list;
}
// ── IIltFeature ─────────────────────────────────────────────────────────
public void Tick(long nowMs)
{
if (nowMs - _lastPetScan >= 2000)
{
_lastPetScan = nowMs;
RebuildPetSnapshot(autoAppraise: true);
// Host reads (and appraisal requests) happen here, never on the render thread.
_uiRefillActive = RefillCharmActive();
_uiMasteryActive = MasteryCharmActive();
_uiHasCasting = _ctx.Inventory.HasCastingSupplies();
}
if (nowMs - _lastHealThink >= 250)
{
_lastHealThink = nowMs;
TickHealing(nowMs);
}
if (nowMs - _lastPresenceThink >= 1000)
{
_lastPresenceThink = nowMs;
var pet = FindOwnPet();
_uiActivePet = pet?.Name ?? string.Empty;
TickCosmetic(nowMs, pet);
UpdateHudPetLine(pet);
}
}
/// <summary>Refreshes the Mini Remote's pet name / status pair (pump thread).</summary>
private void UpdateHudPetLine(WorldObject? pet)
{
if (pet != null)
{
_hudPetName = ResolveActiveEssence(pet)?.Name ?? pet.Name;
_hudPetStatus = _heal != HealState.Idle ? "Healing" : "Out";
return;
}
var next = ChosenEssence(IltPetKind.Combat);
if (next == null) { _hudPetName = string.Empty; _hudPetStatus = string.Empty; return; }
_hudPetName = next.Name;
_hudPetStatus = _ctx.Inventory.Uses(next) == 0 && !AllowSummonOnEmpty() ? "Empty" : "Ready";
}
public bool OnChat(string text)
{
// "<pet> casts Heal Other ... and restores N points of your health."
if (_heal == HealState.Summoning
&& text.Contains("casts", StringComparison.OrdinalIgnoreCase)
&& text.Contains("heal other", StringComparison.OrdinalIgnoreCase)
&& text.Contains("restores", StringComparison.OrdinalIgnoreCase)
&& text.Contains("points of your health", StringComparison.OrdinalIgnoreCase))
{
if (S.AutoDespawnAfterHeal)
{
_heal = HealState.Despawning;
_despawnAt = IltHubContext.NowMs + 1000;
_healStatus = "heal landed, dismissing";
}
else
{
EndHealCycle(IltHubContext.NowMs, "heal landed");
}
}
return false;
}
public void OnLogout()
{
_heal = HealState.Idle;
_pets = Array.Empty<IltPetStats>();
_uiActivePet = string.Empty;
_lastSummonEssenceId = 0;
_cosmeticOutEssenceId = 0;
_cosmeticNextAt = 0;
}
// ── Healing pet ─────────────────────────────────────────────────────────
private void TickHealing(long now)
{
if (!S.HealingEnabled)
{
if (_heal != HealState.Idle) { _heal = HealState.Idle; _healStatus = "off"; }
return;
}
switch (_heal)
{
case HealState.Idle:
{
if (now < _healCooldownUntil) return;
var (cur, max) = _ctx.Inventory.PlayerHealth();
if (max == 0) return;
int pct = (int)(cur * 100 / max);
if (pct >= Math.Clamp(S.HealthThresholdPercent, 1, 99)) { _healStatus = $"HP {pct}% ok"; return; }
if (S.MinHealthPoints > 0 && cur < S.MinHealthPoints) { _healStatus = "HP below minimum, not summoning"; return; }
if (_ctx.Inventory.IsBusy) return;
if (AnyOwnPetPresent()) { _healStatus = "another pet is out"; return; }
var essence = FindHealEssence();
if (essence == null) { _healStatus = "no heal-pet essence found"; return; }
if (_ctx.Inventory.Uses(essence) == 0 && !AllowSummonOnEmpty()) { _healStatus = "heal-pet essence is empty"; return; }
if (!_ctx.Inventory.Use(essence)) return;
_healEssenceId = essence.Id;
_lastSummonEssenceId = essence.Id;
_healStartedAt = now;
_heal = HealState.Summoning;
_healStatus = $"summoning heal pet (HP {pct}%)";
break;
}
case HealState.Summoning:
{
long timeout = Math.Max(5, S.PetTimeoutSeconds) * 1000L;
if (now - _healStartedAt < timeout) return;
// No heal seen in time: dismiss only if the pet is actually up.
if (AnyOwnPetPresent()) UseHealEssence();
EndHealCycle(now, "timed out waiting for heal");
break;
}
case HealState.Despawning:
{
if (now < _despawnAt || _ctx.Inventory.IsBusy) return;
if (AnyOwnPetPresent()) UseHealEssence();
EndHealCycle(now, "dismissed");
break;
}
}
}
private void EndHealCycle(long now, string why)
{
_heal = HealState.Idle;
_healCooldownUntil = now + Math.Max(1, S.RespawnDelaySeconds) * 1000L;
_healStatus = why;
}
private void UseHealEssence()
{
var cache = _ctx.Inventory.Cache;
var essence = cache?[_healEssenceId];
if (essence != null) _ctx.Inventory.Use(essence);
}
// ── Active pet ──────────────────────────────────────────────────────────
/// <summary>The live "&lt;Me&gt;'s …" creature (server pet naming), or null.</summary>
private WorldObject? FindOwnPet()
{
var cache = _ctx.Inventory.Cache;
if (cache == null || _ctx.CharName.Length == 0) return null;
string prefix = _ctx.CharName + "'s ";
return cache.GetLandscape().FirstOrDefault(wo => wo != null && wo.Name.StartsWith(prefix, StringComparison.Ordinal));
}
private bool AnyOwnPetPresent() => FindOwnPet() != null;
/// <summary>"Fire Banshee Essence (250)" → "Fire Banshee": the part the summoned creature is named after.</summary>
private static string EssenceBaseName(string essenceName)
{
int i = essenceName.IndexOf(" Essence", StringComparison.OrdinalIgnoreCase);
return (i > 0 ? essenceName[..i] : essenceName).Trim();
}
private static bool PetMatchesEssence(WorldObject pet, WorldObject essence) => PetMatchesEssence(pet, essence.Name);
private static bool PetMatchesEssence(WorldObject pet, string essenceName)
{
string b = EssenceBaseName(essenceName);
return b.Length > 0 && pet.Name.Contains(b, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Essence that summoned <paramref name="pet"/>: the longest essence base name contained
/// in the creature's name, else the last essence this tab / the heal cycle used.
/// </summary>
private WorldObject? ResolveActiveEssence(WorldObject pet)
{
WorldObject? best = null;
int bestLen = 0;
WorldObject? last = null;
foreach (var wo in _ctx.Inventory.Items())
{
if (wo.Id == _lastSummonEssenceId) last = wo;
if (ClassifyKind(wo, out _) == null) continue;
string b = EssenceBaseName(wo.Name);
if (b.Length > bestLen && pet.Name.Contains(b, StringComparison.OrdinalIgnoreCase))
{
best = wo;
bestLen = b.Length;
}
}
return best ?? last;
}
// ── Cosmetic pet ────────────────────────────────────────────────────────
/// <summary>Keeps the chosen cosmetic pet summoned while nothing else needs the pet slot.</summary>
private void TickCosmetic(long now, WorldObject? pet)
{
if (!S.KeepCosmeticOut) { _cosmeticStatus = "off"; return; }
if (string.IsNullOrWhiteSpace(S.CosmeticPetName)) { _cosmeticStatus = "no cosmetic pet ticked"; return; }
if (pet != null)
{
_cosmeticStatus = PetMatchesEssence(pet, S.CosmeticPetName) ? "out" : "another pet is out";
return;
}
if (now < _cosmeticNextAt || _heal != HealState.Idle || _ctx.Inventory.IsBusy) return;
if (!_ctx.Inventory.InPeaceMode) { _cosmeticStatus = "waiting for peace mode"; return; }
var settings = _ctx.Settings;
if (settings != null && settings.IsMacroRunning && settings.SummonPets) { _cosmeticStatus = "combat summoner is active"; return; }
var essence = FindCarried(S.CosmeticPetName);
if (essence == null) { _cosmeticStatus = "essence not carried"; return; }
if (_ctx.Inventory.Uses(essence) == 0 && !AllowSummonOnEmpty())
{
_cosmeticStatus = "essence is empty";
_cosmeticNextAt = now + 30_000;
return;
}
if (!_ctx.Inventory.Use(essence)) return;
_cosmeticOutEssenceId = essence.Id;
_lastSummonEssenceId = essence.Id;
// Covers the summon round-trip so the pet isn't re-summoned before it appears.
_cosmeticNextAt = now + Math.Max(5, S.CosmeticRespawnSeconds) * 1000L;
_cosmeticStatus = "summoning";
RynthLog.Trace(LogCat.IltPets, $"cosmetic pet summon: {essence.Name}");
}
// ── Manual actions (pump thread) ────────────────────────────────────────
/// <summary>Summons from <paramref name="essenceId"/>, or the current type's chosen pet when 0.</summary>
private void SummonPet(int essenceId, IltPetKind kind)
{
if (FindOwnPet() is { } outPet) { _ctx.Chat($"[Mini Remote] {outPet.Name} is already out — Despawn it first."); return; }
if (_heal != HealState.Idle) { _ctx.Chat("[Mini Remote] The heal-pet cycle is running."); return; }
if (_ctx.Inventory.IsBusy) { _ctx.Chat("[Mini Remote] Busy — try again in a moment."); return; }
WorldObject? essence = essenceId != 0 ? _ctx.Inventory.Items().FirstOrDefault(w => w.Id == essenceId) : ChosenEssence(kind);
if (essence == null) { _ctx.Chat($"[Mini Remote] No {KindNames[(int)kind].ToLowerInvariant()} pet selected."); return; }
if (_ctx.Inventory.Uses(essence) == 0 && !AllowSummonOnEmpty()) { _ctx.Chat($"[Mini Remote] {essence.Name} has no uses left."); return; }
if (!_ctx.Inventory.Use(essence)) return;
_lastSummonEssenceId = essence.Id;
if (NameIs(essence, S.CosmeticPetName)) _cosmeticOutEssenceId = essence.Id;
RynthLog.Trace(LogCat.IltPets, $"manual summon: {essence.Name}");
}
/// <summary>Dismisses the pet that is out by using the essence that summoned it again.</summary>
private void DespawnPet()
{
var pet = FindOwnPet();
if (pet == null) { _ctx.Chat("[Mini Remote] No pet is out."); return; }
if (_ctx.Inventory.IsBusy) { _ctx.Chat("[Mini Remote] Busy — try again in a moment."); return; }
var essence = ResolveActiveEssence(pet);
if (essence == null) { _ctx.Chat($"[Mini Remote] Couldn't find the essence for {pet.Name}."); return; }
if (!_ctx.Inventory.Use(essence)) return;
// A manual dismiss shouldn't be undone straight away by "Keep cosmetic pet out".
_cosmeticNextAt = IltHubContext.NowMs + Math.Max(5, S.CosmeticRespawnSeconds) * 1000L;
if (essence.Id == _cosmeticOutEssenceId) _cosmeticOutEssenceId = 0;
RynthLog.Trace(LogCat.IltPets, $"manual despawn: {pet.Name} via {essence.Name}");
}
/// <summary>The pet the type's tick selects: first combat priority, the heal pet, or the cosmetic pet.</summary>
private WorldObject? ChosenEssence(IltPetKind kind)
{
switch (kind)
{
case IltPetKind.Healing:
return FindHealEssence();
case IltPetKind.Cosmetic:
return FindCarried(S.CosmeticPetName);
default:
var rules = PetRules();
foreach (var r in rules)
{
var wo = _ctx.Inventory.Items().FirstOrDefault(w => w.Id == r.Id || NameIs(w, r.Name));
if (wo != null) return wo;
}
return null;
}
}
/// <summary>
/// Requests appraisal for every carried pet (refreshes bond / potency after fights) and
/// for un-appraised pet-named items, whose type is only known once the appraisal lands.
/// </summary>
private void ScanPack()
{
int pets = 0, candidates = 0;
foreach (var wo in _ctx.Inventory.Items())
{
if (ClassifyKind(wo, out _) != null)
{
if (_ctx.Inventory.RequestAppraisal(wo)) pets++;
}
else if (IsUnconfirmedCandidate(wo) && _ctx.Inventory.RequestAppraisal(wo))
{
candidates++;
}
}
if (pets == 0 && candidates == 0)
_ctx.Chat("[Mini Remote] Pets were appraised recently.");
else
_ctx.Chat(candidates > 0
? $"[Mini Remote] Appraising {pets} pet(s) and checking {candidates} pet-named item(s)…"
: $"[Mini Remote] Appraising {pets} pet(s)…");
RebuildPetSnapshot(autoAppraise: false);
}
/// <summary>Gives the item selected in the game a summon type (pump thread).</summary>
private void AddSelectedAs(IltPetKind kind)
{
if (!_ctx.Host.HasGetSelectedItemId) { _ctx.Chat("[Mini Remote] This client build can't read the selected item."); return; }
int id = unchecked((int)_ctx.Host.GetSelectedItemId());
var wo = _ctx.Inventory.Items().FirstOrDefault(w => w.Id == id);
if (wo == null) { _ctx.Chat("[Mini Remote] Select a pet essence in your pack first."); return; }
SetKind(wo.Id, wo.Name, kind);
_ctx.Chat($"[Mini Remote] {wo.Name} added as a {KindNames[(int)kind].ToLowerInvariant()} pet.");
}
/// <summary>
/// Re-types an essence (null = back to auto classification) and drops it from the other
/// types' selections so a pet is only ever chosen under one type.
/// </summary>
private void SetKind(int id, string name, IltPetKind? kind)
{
S.Assignments.RemoveAll(a => a.Name.Equals(name, StringComparison.OrdinalIgnoreCase));
if (kind is { } k) S.Assignments.Add(new IltPetAssignment { Name = name, Kind = (int)k });
if (kind != IltPetKind.Combat && PetRules().Any(r => r.Id == id || r.Name.Equals(name, StringComparison.OrdinalIgnoreCase)))
SetCombatSelected(id, name, false);
if (kind != IltPetKind.Healing && S.HealPetName.Trim().Equals(name, StringComparison.OrdinalIgnoreCase))
S.HealPetName = string.Empty;
if (kind != IltPetKind.Cosmetic && S.CosmeticPetName.Trim().Equals(name, StringComparison.OrdinalIgnoreCase))
S.CosmeticPetName = string.Empty;
RebuildPetSnapshot(autoAppraise: false);
}
/// <summary>Applies a roster tick for the row's type (pump thread).</summary>
private void SetSelected(int id, string name, IltPetKind kind, bool on)
{
switch (kind)
{
case IltPetKind.Healing: S.HealPetName = on ? name : string.Empty; break;
case IltPetKind.Cosmetic: S.CosmeticPetName = on ? name : string.Empty; break;
default: SetCombatSelected(id, name, on); break;
}
RebuildPetSnapshot(autoAppraise: false);
}
// ── Combat summon list (ConsumableRules Type=="Pet") ────────────────────
private List<ConsumableRule> PetRules()
=> _ctx.Settings?.ConsumableRules.Where(r => r.Type.Equals("Pet", StringComparison.OrdinalIgnoreCase)).ToList()
?? new List<ConsumableRule>();
/// <summary>Adds or removes an essence from the PetManager list (pump thread).</summary>
private void SetCombatSelected(int id, string name, bool on)
{
var settings = _ctx.Settings;
if (settings == null) return;
settings.ConsumableRules.RemoveAll(r => r.Type.Equals("Pet", StringComparison.OrdinalIgnoreCase)
&& (r.Id == id || r.Name.Equals(name, StringComparison.OrdinalIgnoreCase)));
if (on) settings.ConsumableRules.Add(new ConsumableRule { Id = id, Name = name, Type = "Pet" });
_ctx.SaveCombatSettings?.Invoke();
}
/// <summary>Moves a configured essence up (-1) or down (+1) in summon priority (pump thread).</summary>
private void MovePriority(int id, int delta)
{
var settings = _ctx.Settings;
if (settings == null) return;
var list = settings.ConsumableRules;
int idx = list.FindIndex(r => r.Id == id && r.Type.Equals("Pet", StringComparison.OrdinalIgnoreCase));
if (idx < 0) return;
// Find the neighbouring Pet rule in the requested direction.
int j = idx + delta;
while (j >= 0 && j < list.Count && !list[j].Type.Equals("Pet", StringComparison.OrdinalIgnoreCase)) j += delta;
if (j < 0 || j >= list.Count) return;
(list[idx], list[j]) = (list[j], list[idx]);
_ctx.SaveCombatSettings?.Invoke();
RebuildPetSnapshot(autoAppraise: false);
}
// ── Roster snapshot (pump thread) ───────────────────────────────────────
private void RebuildPetSnapshot(bool autoAppraise)
{
var rules = PetRules();
long unixNow = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
var rows = new List<IltPetStats>();
int appraised = 0;
foreach (var wo in _ctx.Inventory.Items())
{
var kind = ClassifyKind(wo, out bool assigned);
if (kind == null)
{
// Pet-named but unconfirmed: its appraisal decides whether it is a pet device.
if (autoAppraise && appraised < AutoAppraisePerScan && IsUnconfirmedCandidate(wo)
&& _ctx.Inventory.RequestAppraisal(wo))
appraised++;
continue;
}
var s = IltPetStatsReader.Read(_ctx.Host, _ctx.Inventory, wo, unixNow);
s.Kind = kind.Value;
s.KindAssigned = assigned;
int pri = rules.FindIndex(r => r.Id == wo.Id || r.Name.Equals(wo.Name, StringComparison.OrdinalIgnoreCase));
s.Priority = pri >= 0 ? pri : int.MaxValue;
s.Selected = s.Kind switch
{
IltPetKind.Healing => NameIs(wo, S.HealPetName),
IltPetKind.Cosmetic => NameIs(wo, S.CosmeticPetName),
_ => pri >= 0,
};
rows.Add(s);
// Stats beyond uses need an appraisal; trickle the requests for un-ID'd essences.
if (autoAppraise && !s.HasId && appraised < AutoAppraisePerScan && _ctx.Inventory.RequestAppraisal(wo))
appraised++;
}
_pets = rows.ToArray();
}
// ── UI (render thread) ──────────────────────────────────────────────────
public void Render()
{
var settings = _ctx.Settings;
if (settings == null) { ImGui.TextDisabled("Not logged in."); return; }
RenderRosterHeader(settings);
RenderRosterTable();
// The tab is universal; the charms and the /pets and /shinies logs are ILT's.
bool ilt = _ctx.Options.IsIltLikeWorld;
if (ilt)
{
ImGui.Separator();
RenderCharms();
}
ImGui.Separator();
RenderHealing();
if (ilt)
{
ImGui.Separator();
RenderRosters();
}
}
/// <summary>Type / Sort combos, action buttons, the active-summon line and per-type options.</summary>
private void RenderRosterHeader(LegacyUiSettings settings)
{
var kind = (IltPetKind)Math.Clamp(S.RosterKind, 0, 2);
ImGui.TextUnformatted("Type");
ImGui.SameLine();
ImGui.SetNextItemWidth(100);
int k = (int)kind;
if (ImGui.Combo("##iltpetkind", ref k, KindNames, KindNames.Length)) { S.RosterKind = k; kind = (IltPetKind)k; _highlightId = 0; }
ImGui.SameLine();
ImGui.TextUnformatted("Sort");
ImGui.SameLine();
ImGui.SetNextItemWidth(110);
int sort = Math.Clamp(S.RosterSort, 0, SortNames.Length - 1);
if (ImGui.Combo("##iltpetsort", ref sort, SortNames, SortNames.Length)) S.RosterSort = sort;
int target = _highlightId;
var summonKind = kind;
if (ImGui.Button("Summon")) _ctx.Post(() => SummonPet(target, summonKind));
if (ImGui.IsItemHovered()) ImGui.SetTooltip("Summon the highlighted pet (or this type's ticked pet).");
ImGui.SameLine();
if (ImGui.Button("Despawn")) _ctx.Post(DespawnPet);
if (ImGui.IsItemHovered()) ImGui.SetTooltip("Dismiss the pet that is out.");
ImGui.SameLine();
if (ImGui.Button("Scan pack")) _ctx.Post(ScanPack);
if (ImGui.IsItemHovered()) ImGui.SetTooltip("Appraise every pet to refresh bond, potency and breeding, and check pet-named items\n(an \"... Essence\" name alone isn't enough — the item must be a summoning pet device).");
ImGui.SameLine();
if (ImGui.Button("Add sel.")) _ctx.Post(() => AddSelectedAs(summonKind));
if (ImGui.IsItemHovered()) ImGui.SetTooltip($"Make the item selected in your pack a {KindNames[(int)kind].ToLowerInvariant()} pet.");
string active = _uiActivePet;
if (active.Length > 0) ImGui.TextColored(LegacyDashboardRenderer.ColTeal, "Active summon: " + active);
else ImGui.TextDisabled("Active summon: none");
switch (kind)
{
case IltPetKind.Combat:
{
bool summon = settings.SummonPets;
if (ImGui.Checkbox("Summon when monsters are near", ref summon)) _ctx.Post(() => { settings.SummonPets = summon; _ctx.SaveCombatSettings?.Invoke(); });
ImGui.SameLine();
int minMobs = settings.PetMinMonsters;
ImGui.SetNextItemWidth(90);
if (ImGui.InputInt("Min monsters", ref minMobs)) _ctx.Post(() => { settings.PetMinMonsters = Math.Max(1, minMobs); _ctx.SaveCombatSettings?.Invoke(); });
bool refill = settings.PetAutoRefill;
if (ImGui.Checkbox("Refill empty essences with Encapsulated Spirit", ref refill)) _ctx.Post(() => { settings.PetAutoRefill = refill; _ctx.SaveCombatSettings?.Invoke(); });
ImGui.TextDisabled("Tick pets to add them to the summon list; with Sort = Priority the arrows set the order.");
break;
}
case IltPetKind.Healing:
ImGui.TextDisabled("Tick one heal pet (none ticked = first Healing Buddy / Dule box). Settings are below.");
break;
case IltPetKind.Cosmetic:
{
bool keep = S.KeepCosmeticOut;
if (ImGui.Checkbox("Keep cosmetic pet out", ref keep)) S.KeepCosmeticOut = keep;
if (ImGui.IsItemHovered()) ImGui.SetTooltip("Peace mode only. Dismissed automatically when the combat summoner needs the pet slot.");
ImGui.SameLine();
int resp = S.CosmeticRespawnSeconds;
ImGui.SetNextItemWidth(90);
if (ImGui.InputInt("Respawn (s)", ref resp)) S.CosmeticRespawnSeconds = Math.Clamp(resp, 5, 600);
ImGui.TextDisabled("Tick one cosmetic pet. Status: " + _cosmeticStatus);
break;
}
}
}
/// <summary>Sorted rows of the current type, cached until the snapshot / type / sort changes.</summary>
private IltPetStats[] CurrentView()
{
var src = _pets;
int kind = Math.Clamp(S.RosterKind, 0, 2);
int sort = Math.Clamp(S.RosterSort, 0, SortNames.Length - 1);
if (!ReferenceEquals(src, _viewSource) || kind != _viewKind || sort != _viewSort)
{
_view = IltPetStatsReader.Sort(src.Where(p => (int)p.Kind == kind), (IltPetSort)sort);
_viewSource = src;
_viewKind = kind;
_viewSort = sort;
}
return _view;
}
/// <summary>One table row per pet: tick · three stat lines (highlight / right-click menu) · priority arrows.</summary>
private void RenderRosterTable()
{
var rows = CurrentView();
var kind = (IltPetKind)Math.Clamp(S.RosterKind, 0, 2);
bool showArrows = kind == IltPetKind.Combat && S.RosterSort == (int)IltPetSort.Priority;
if (rows.Length == 0)
{
ImGui.TextDisabled(kind == IltPetKind.Cosmetic
? "No cosmetic pets yet — select an essence in your pack and press Add sel., or right-click a pet in another type."
: $"No {KindNames[(int)kind].ToLowerInvariant()} pet essences carried.");
return;
}
float lineH = ImGui.GetTextLineHeightWithSpacing();
float tableH = Math.Min(320f, rows.Length * (lineH * 3 + 6) + 8);
if (!ImGui.BeginTable("##iltpets", 3, ImGuiTableFlags.RowBg | ImGuiTableFlags.BordersInnerV | ImGuiTableFlags.ScrollY, new Vector2(0, tableH)))
return;
ImGui.TableSetupColumn("##sel", ImGuiTableColumnFlags.WidthFixed, 26);
ImGui.TableSetupColumn("##pet");
ImGui.TableSetupColumn("##ord", ImGuiTableColumnFlags.WidthFixed, showArrows ? 52 : 1);
foreach (var r in rows)
{
ImGui.TableNextRow();
ImGui.TableNextColumn();
bool on = r.Selected;
if (ImGui.Checkbox($"##psel{r.Id}", ref on))
{
var row = r;
_ctx.Post(() => SetSelected(row.Id, row.Name, row.Kind, on));
}
ImGui.TableNextColumn();
Vector2 start = ImGui.GetCursorPos();
if (ImGui.Selectable($"##prow{r.Id}", _highlightId == r.Id, ImGuiSelectableFlags.AllowOverlap, new Vector2(0, lineH * 3 - ImGui.GetStyle().ItemSpacing.Y)))
_highlightId = _highlightId == r.Id ? 0 : r.Id;
RenderRowContextMenu(r);
ImGui.SetCursorPos(start);
ImGui.TextColored(DamageColor(r.DamageType), r.Line1);
ImGui.TextColored(LegacyDashboardRenderer.ColAmber, " " + r.Line2);
if (r.UsesMax > 0 && r.UsesCur == 0) ImGui.TextColored(LegacyDashboardRenderer.ColHp, " " + r.Line3);
else ImGui.TextDisabled(" " + r.Line3);
ImGui.TableNextColumn();
if (showArrows && r.Selected)
{
int id = r.Id;
if (ImGui.ArrowButton($"##pup{r.Id}", ImGuiDir.Up)) _ctx.Post(() => MovePriority(id, -1));
ImGui.SameLine();
if (ImGui.ArrowButton($"##pdn{r.Id}", ImGuiDir.Down)) _ctx.Post(() => MovePriority(id, +1));
}
}
ImGui.EndTable();
}
/// <summary>Right-click menu on a roster row: summon / move to another type / clear override.</summary>
private void RenderRowContextMenu(IltPetStats r)
{
if (!ImGui.BeginPopupContextItem($"##pctx{r.Id}")) return;
var row = r;
if (ImGui.MenuItem("Summon")) _ctx.Post(() => SummonPet(row.Id, row.Kind));
ImGui.Separator();
for (int i = 0; i < KindNames.Length; i++)
{
if (i == (int)r.Kind) continue;
var to = (IltPetKind)i;
if (ImGui.MenuItem("Move to " + KindNames[i])) _ctx.Post(() => SetKind(row.Id, row.Name, to));
}
if (r.KindAssigned && ImGui.MenuItem("Clear type override"))
_ctx.Post(() => SetKind(row.Id, row.Name, null));
ImGui.EndPopup();
}
/// <summary>Line-1 colour by the pet's damage type (white when unknown / not appraised).</summary>
private static Vector4 DamageColor(string damageType) => damageType switch
{
"Fire" => new Vector4(1.00f, 0.55f, 0.30f, 1f),
"Cold" => new Vector4(0.55f, 0.80f, 1.00f, 1f),
"Acid" => new Vector4(0.55f, 0.95f, 0.45f, 1f),
"Lightning" => new Vector4(0.85f, 0.70f, 1.00f, 1f),
"Nether" => new Vector4(0.75f, 0.50f, 0.90f, 1f),
_ => new Vector4(0.95f, 0.95f, 0.95f, 1f),
};
private void RenderCharms()
{
ImGui.TextColored(LegacyDashboardRenderer.ColTeal, "Pet charms");
bool refillOff = _ctx.Options.IsOff(IltFeature.PetRefill);
ImGui.TextUnformatted("Summon Essence Refill: " + (refillOff ? "disabled on this server" : _uiRefillActive ? "ON" : "off / not carried"));
ImGui.BeginDisabled(refillOff);
bool usePath = S.UsePyrealRefillPath;
if (ImGui.Checkbox("Summon from empty essences while the refill charm is ON (spends banked pyreals)", ref usePath))
S.UsePyrealRefillPath = usePath;
ImGui.EndDisabled();
ImGui.TextUnformatted("Universal Summoning Mastery: "
+ (_ctx.Options.IsOff(IltFeature.UniversalMastery) ? "disabled on this server" : _uiMasteryActive ? "ON" : "off / not carried"));
if (!_ctx.Options.IsOff(IltFeature.RequireComps) && !_uiHasCasting)
ImGui.TextColored(LegacyDashboardRenderer.ColAmber, "No spell components or Infinite Casting Stone carried.");
}
private void RenderHealing()
{
if (!ImGui.CollapsingHeader("Healing pet settings")) return;
bool en = S.HealingEnabled;
if (ImGui.Checkbox("Summon heal pet when health is low", ref en)) S.HealingEnabled = en;
string healPet = S.HealPetName;
ImGui.TextDisabled("Heal pet: " + (string.IsNullOrWhiteSpace(healPet) ? "auto (Healing Buddy / Dule box)" : healPet)
+ " — tick one under Type = Healing.");
int thr = S.HealthThresholdPercent;
ImGui.SetNextItemWidth(160);
if (ImGui.SliderInt("Health % trigger", ref thr, 10, 99)) S.HealthThresholdPercent = thr;
int minHp = S.MinHealthPoints;
ImGui.SetNextItemWidth(100);
if (ImGui.InputInt("Don't summon below HP", ref minHp, 10)) S.MinHealthPoints = Math.Max(0, minHp);
bool desp = S.AutoDespawnAfterHeal;
if (ImGui.Checkbox("Dismiss after the heal", ref desp)) S.AutoDespawnAfterHeal = desp;
int resp = S.RespawnDelaySeconds;
ImGui.SetNextItemWidth(100);
if (ImGui.InputInt("Respawn delay (s)", ref resp)) S.RespawnDelaySeconds = Math.Max(1, resp);
int to = S.PetTimeoutSeconds;
ImGui.SetNextItemWidth(100);
if (ImGui.InputInt("Heal timeout (s)", ref to)) S.PetTimeoutSeconds = Math.Max(5, to);
ImGui.TextDisabled("Status: " + _healStatus);
}
private void RenderRosters()
{
RenderRoster("Pet log", false, IltFeature.Pets, S.PetLog);
RenderRoster("Shiny log", true, IltFeature.Shinies, S.ShinyLog);
}
private void RenderRoster(string label, bool shinies, string key, List<string> list)
{
if (_ctx.Options.IsOff(key)) return;
var snap = list.ToArray();
if (ImGui.TreeNode($"{label} ({snap.Length})##{key}"))
{
if (ImGui.SmallButton($"Refresh##{key}")) _ctx.Post(() => RequestRoster(shinies));
foreach (string s in snap) ImGui.BulletText(s);
ImGui.TreePop();
}
}
}

View file

@ -0,0 +1,775 @@
// IltProgression.cs — Augmentation and Enlightenment planners, drawn by the engine's
// Skills panel (Progression tab) from AppendSnapshotJson; edits arrive via HandleRemote.
//
// Augs : "/aug" levels + the per-server cost rules in IltAugCosts (UB's ILT model by default:
// level i costs base + (i-1)*(base*LP/100), times 1/4/8/16/24 from S1..S4), coins per level.
// Enl : tier material/luminance table, requirement checklist, "/enl" on confirm. The
// server pops its own Yes/No dialog — the host cannot (and must not) click it.
// Optional auto-enlighten is disarmed every session and needs a hard confirm.
// XP : the Skills panel plans attribute/vital raises from the client's exact XP tables;
// this module spends unassigned XP ("/attr") before an auto-enlighten, and owns the
// infinite-attribute raiser (IltAttributeRaiser: server costs from "/xp all", manual
// or timed raises in a chosen order) drawn in the same tab.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace RynthCore.Plugin.RynthAi.IltHub;
internal sealed class IltProgression : IIltFeature
{
// ── Augmentation cost rules ─────────────────────────────────────────────
/// <summary>Per-server aug cost rules (UB's ILT model unless this world was changed).</summary>
public IltAugCosts AugCosts { get; } = new();
/// <summary>The rules for the world we're on.</summary>
private IltAugCostProfile AugProfile => AugCosts.For(_ctx.Options.WorldName);
// ── Enlightenment ───────────────────────────────────────────────────────
private const int BaseLevelForEnl = 275;
private const long AutoEnlCooldownMs = 60_000;
private const uint SpellVitae = 666;
/// <summary>Materials for reaching enlightenment level <paramref name="t"/> (one step).</summary>
public static (string Item, uint Wcid, int Count, decimal Lum) EnlStepCost(int t)
{
if (t <= 5) return ("none", 0, 0, 0);
int count = t - 5;
if (t <= 50) return ("Enlightenment Tokens", IltInventory.WcidEnlToken, count, 0);
if (t <= 150) return ("Enlightenment Tokens", IltInventory.WcidEnlToken, count, t * 100_000_000m);
if (t <= 300) return ("Enlightenment Medallions", IltInventory.WcidEnlMedallion, count, t * 1_000_000_000m);
decimal mult = 1m + 0.5m * ((t - 300 - 1) / 50);
decimal lum = Math.Ceiling(t * 2_000_000_000m * mult);
return t <= 325 ? ("Enlightenment Sigils", IltInventory.WcidEnlSigil, count, lum)
: ("Enlightenment Crests", IltInventory.WcidEnlCrest, count, lum);
}
// ── XP ──────────────────────────────────────────────────────────────────
/// <summary>/attr abbreviation, display name, attribute stype (0 = vital), vital stype.</summary>
private static readonly (string Abbr, string Name, uint Attr, uint Vital)[] Stats =
{
("str", "Strength", 1, 0), ("end", "Endurance", 2, 0), ("coo", "Coordination", 4, 0),
("qui", "Quickness", 3, 0), ("foc", "Focus", 5, 0), ("sel", "Self", 6, 0),
("hea", "Health", 0, 1), ("sta", "Stamina", 0, 3), ("man", "Mana", 0, 5),
};
private readonly IltHubContext _ctx;
private readonly Dictionary<string, int> _augLevels = new(StringComparer.OrdinalIgnoreCase);
private volatile string _augStatus = "not loaded";
// Opening the Progression tab pulls "/aug" once per login when nothing has loaded the levels yet.
private bool _augAutoTried;
// Cached player facts for the render thread (refreshed in Tick).
private volatile int _enl, _level, _freeSlots;
private long _unassignedXp;
private volatile bool _peace, _hasVitae;
private readonly long[] _enlHave = new long[4]; // tokens, medallions, sigils, crests
// 301-325 sigil chain stock (pack items by name; EnlightenedCoins = bank + pack). Pump thread only.
private IltSigilStock _chain = new();
private long _lastFactsAt;
private readonly uint[] _enchIds = new uint[256];
private readonly double[] _enchExp = new double[256];
// Auto-enlighten (armed only after the in-session confirm).
private bool _autoArmed;
private long _lastAutoCheck;
private long _lastEnlSentAt = -AutoEnlCooldownMs;
private volatile string _enlStatus = string.Empty;
// XP spend-before-enlighten loop.
private bool _spending;
private int _spendIdx, _spendSent, _spendNoProgress;
private long _spendLastAt, _spendLastXp;
private Action? _afterSpend;
/// <summary>Infinite-attribute raiser (Progression tab "Attribute raiser" section).</summary>
public IltAttributeRaiser Attributes { get; }
public IltProgression(IltHubContext ctx)
{
_ctx = ctx;
// Never two /attr spenders at once: the raiser waits while the spend-before-/enl loop runs.
Attributes = new IltAttributeRaiser(ctx) { HoldOff = () => _spending };
}
private IltCharacterState C => _ctx.State.Character;
// ── Commands ────────────────────────────────────────────────────────────
public void RequestAugs()
{
RynthLog.Trace(LogCat.IltProgression, $"RequestAugs()");
if (_ctx.Options.IsOff(IltFeature.Aug) || _ctx.Capture.IsPending("/aug")) return;
_augStatus = "loading...";
_ctx.Capture.Enqueue(new IltChatRequest
{
Command = "/aug",
IsResponseLine = t => t.StartsWith("---") || t.Contains("Augmentation Levels", StringComparison.OrdinalIgnoreCase) || IltParse.AugLine.IsMatch(t),
IdleEndMs = 2000,
FirstLineTimeoutMs = 15000,
Eat = true,
OnComplete = r =>
{
if (r.UnknownCommand) { _ctx.Options.Set(IltFeature.Aug, IltTri.Off); _augStatus = "/aug not available"; return; }
ApplyAugLines(r.Lines);
},
});
}
/// <summary>Parses "/aug" output (also fed from the login probe).</summary>
public void ApplyAugLines(List<string> lines)
{
RynthLog.Trace(LogCat.IltProgression, $"ApplyAugLines(lines={lines.Count})");
int n = 0;
foreach (string l in lines)
{
var m = IltParse.AugLine.Match(l.Trim());
if (!m.Success) continue;
string key = m.Groups[1].Value.ToLowerInvariant();
if (key == "specialize") key = "specialization";
lock (_augLevels) _augLevels[key] = (int)IltParse.ParseLeadingLong(m.Groups[2].Value);
n++;
}
_augStatus = n > 0 ? $"{n} aug types @ {DateTime.Now:t}" : "no aug lines in reply";
}
/// <summary>Sends "/enl" (server shows the confirmation dialog). Pump thread.</summary>
public void SendEnlighten(string why)
{
RynthLog.Trace(LogCat.IltProgression, $"SendEnlighten(why='{why}')");
if (!_ctx.Host.HasInvokeChatParser) return;
_lastEnlSentAt = IltHubContext.NowMs;
_ctx.Host.InvokeChatParser("/enl");
_enlStatus = $"/enl sent ({why}) - click Yes in the AC dialog to confirm.";
_ctx.Chat("[Mini Remote] " + _enlStatus);
}
// ── IIltFeature ─────────────────────────────────────────────────────────
public void Tick(long nowMs)
{
if (nowMs - _lastFactsAt >= 2000)
{
_lastFactsAt = nowMs;
RefreshFacts();
}
TickSpend(nowMs);
Attributes.Tick(nowMs, holdOff: _spending);
if (_autoArmed && C.AutoEnlightenEnabled && !_spending
&& nowMs - _lastAutoCheck >= Math.Max(10, C.AutoEnlightenCheckSeconds) * 1000L)
{
_lastAutoCheck = nowMs;
TryAutoEnlighten(nowMs);
}
}
public bool OnChat(string text)
{
Attributes.OnChat(text);
if (text.Contains("You have become enlightened", StringComparison.OrdinalIgnoreCase)
|| text.Contains("You have risen to a higher tier of enlightenment", StringComparison.OrdinalIgnoreCase))
{
_enlStatus = "Enlightened! " + DateTime.Now.ToString("t");
_lastFactsAt = 0;
}
return false;
}
public void OnLogout()
{
_autoArmed = false;
_spending = false;
Attributes.OnLogout();
lock (_augLevels) _augLevels.Clear();
_augAutoTried = false;
_augStatus = "not loaded";
}
// ── Facts / auto ────────────────────────────────────────────────────────
private void RefreshFacts()
{
var inv = _ctx.Inventory;
_enl = inv.PlayerInt(IltInventory.IntEnlightenment);
_level = inv.PlayerInt(IltInventory.IntLevel);
_unassignedXp = inv.PlayerQuad(IltInventory.QuadAvailableXp);
_peace = inv.InPeaceMode;
_freeSlots = inv.FreeMainPackSlots();
_enlHave[0] = inv.CountByWcid(IltInventory.WcidEnlToken);
_enlHave[1] = inv.CountByWcid(IltInventory.WcidEnlMedallion);
_enlHave[2] = inv.CountByWcid(IltInventory.WcidEnlSigil);
_enlHave[3] = inv.CountByWcid(IltInventory.WcidEnlCrest);
_chain = new IltSigilStock
{
Sigils = _enlHave[2],
EnlightenedCoins = _ctx.State.Bank.EnlightenedCoins + inv.CountByWcid(IltInventory.WcidEnlightenedCoin),
AscensionCoins = inv.CountByChainName(IltSigilChain.AscensionCoin),
LifebloodElixirs = inv.CountByChainName(IltSigilChain.LifebloodElixir),
LifebloomResins = inv.CountByChainName(IltSigilChain.LifebloomResin),
YalaniTrinkets = inv.CountByChainName(IltSigilChain.YalaniTrinket),
NecrolyticExtracts = inv.CountByChainName(IltSigilChain.NecrolyticExtract),
LifeSplitters = inv.CountByChainName(IltSigilChain.LifeSplitter),
Plants = inv.CountByChainName(IltSigilChain.Plant),
};
_hasVitae = false;
if (_ctx.Host.HasReadPlayerEnchantments)
{
int n = _ctx.Host.ReadPlayerEnchantments(_enchIds, _enchExp, _enchIds.Length);
for (int i = 0; i < Math.Min(n, _enchIds.Length); i++)
if (_enchIds[i] == SpellVitae) { _hasVitae = true; break; }
}
}
private long HaveFor(uint wcid) => wcid switch
{
IltInventory.WcidEnlToken => _enlHave[0],
IltInventory.WcidEnlMedallion => _enlHave[1],
IltInventory.WcidEnlSigil => _enlHave[2],
IltInventory.WcidEnlCrest => _enlHave[3],
_ => 0,
};
/// <summary>Checks the client-visible requirements for the next enlightenment. Empty = ready.</summary>
private List<string> NextEnlBlockers()
{
var list = new List<string>();
int next = _enl + 1;
if (_level < BaseLevelForEnl + _enl) list.Add($"Need character level {BaseLevelForEnl + _enl} (have {_level}).");
if (!_peace) list.Add("Must be in peace mode.");
if (_hasVitae) list.Add("Must not have vitae.");
var cost = EnlStepCost(next);
if (cost.Count > 0 && HaveFor(cost.Wcid) < cost.Count)
{
// Sigils: the server takes finished sigils only, but say how many the craft chain could still make.
string craft = cost.Wcid == IltInventory.WcidEnlSigil
? $"; the craft chain can make {IltParse.N0(IltSigilChain.Fulfillable(_chain) - _chain.Sigils)} more"
: string.Empty;
list.Add($"Need {cost.Count} {cost.Item} (have {HaveFor(cost.Wcid)}{craft}).");
}
if (cost.Lum > 0 && _ctx.State.Bank.Luminance < cost.Lum) list.Add($"Need {IltParse.Compact((double)cost.Lum)} banked luminance.");
return list;
}
private void TryAutoEnlighten(long now)
{
if (_ctx.Options.IsOff(IltFeature.Enl)) return;
if (Attributes.Running) return; // the raiser is spending XP; check again next interval
if (now - _lastEnlSentAt < AutoEnlCooldownMs) return;
if (NextEnlBlockers().Count > 0) return;
if (C.AutoEnlightenSpendXpFirst && _unassignedXp > 0)
StartSpend(() => SendEnlighten("auto"));
else
SendEnlighten("auto");
}
// ── XP spend loop: cycles /attr <abbr> 1 until unassigned XP stops dropping ──
private void StartSpend(Action then)
{
_spending = true;
_spendIdx = 0;
_spendSent = 0;
_spendNoProgress = 0;
_spendLastAt = 0;
_spendLastXp = _ctx.Inventory.PlayerQuad(IltInventory.QuadAvailableXp);
_afterSpend = then;
_enlStatus = "Spending unassigned XP before enlightening...";
}
private void TickSpend(long now)
{
if (!_spending || now - _spendLastAt < 300) return;
_spendLastAt = now;
long xp = _ctx.Inventory.PlayerQuad(IltInventory.QuadAvailableXp);
if (xp < _spendLastXp) _spendNoProgress = 0; else if (_spendSent > 0) _spendNoProgress++;
_spendLastXp = xp;
// Stop after a full stat cycle with no XP drop, when XP is gone, or at the safety cap.
if (xp <= 0 || _spendNoProgress >= Stats.Length || _spendSent >= 300)
{
_spending = false;
var next = _afterSpend;
_afterSpend = null;
next?.Invoke();
return;
}
if (_ctx.Inventory.IsBusy) return;
_ctx.Host.InvokeChatParser($"/attr {Stats[_spendIdx].Abbr} 1");
_spendIdx = (_spendIdx + 1) % Stats.Length;
_spendSent++;
}
// ── Engine Skills panel bridge (pump thread) ────────────────────────────
// The engine's Skills panel draws Augmentations and Enlightenment from this snapshot and
// sends edits back as "prog ..." remote commands (HandleRemote). Planner math stays here so
// the Hub and the Skills panel can never disagree. Numbers are preformatted for display.
/// <summary>Appends <c>"aug":{...},"enl":{...},"attr":{...}</c> to <paramref name="sb"/>. Pump thread.</summary>
public void AppendSnapshotJson(StringBuilder sb)
{
// The snapshot is only polled while the Progression tab is open, so this is "on first view".
EnsureAugs();
Attributes.EnsureCosts();
AppendAugJson(sb);
sb.Append(',');
AppendEnlJson(sb);
sb.Append(',');
Attributes.AppendJson(sb);
}
/// <summary>Pulls "/aug" once per login when the levels haven't been loaded (login probe or by hand).</summary>
private void EnsureAugs()
{
if (_augAutoTried || _ctx.Options.IsOff(IltFeature.Aug) || !_ctx.Host.HasInvokeChatParser) return;
bool loaded;
lock (_augLevels) loaded = _augLevels.Count > 0;
_augAutoTried = true;
if (!loaded) RequestAugs();
}
/// <summary>One aug's plan line: current level, clamped target, luminance and coins to get there.</summary>
private readonly record struct AugPlan(IltAugCostRow Def, string Label, int Cur, int Tgt, int Ceiling, decimal Lum, long Coins)
{
public int Inc => Tgt - Cur;
}
private List<AugPlan> BuildAugPlan()
{
Dictionary<string, int> levels;
lock (_augLevels) levels = new Dictionary<string, int>(_augLevels, StringComparer.OrdinalIgnoreCase);
var profile = AugProfile;
var plan = new List<AugPlan>(profile.Augs.Count);
foreach (var a in profile.Augs)
{
int cur = levels.TryGetValue(a.Key, out int c) ? c : 0;
int ceiling = IltAugCosts.Ceiling(a, cur);
int tgt = Math.Clamp(C.AugTargets.TryGetValue(a.Key, out int t) ? t : cur, cur, ceiling);
plan.Add(new AugPlan(a, IltAugCosts.Label(a.Key), cur, tgt, ceiling,
IltAugCosts.LumCost(a, profile.Multipliers, cur, tgt), (long)(tgt - cur) * a.CoinsPerLevel));
}
return plan;
}
private void AppendAugJson(StringBuilder sb)
{
var plan = BuildAugPlan();
sb.Append("\"aug\":{\"off\":").Append(Bool(_ctx.Options.IsOff(IltFeature.Aug)));
Str(sb, "status", _augStatus);
sb.Append(",\"lumPerCoin\":").Append(C.LumPerEnlightenedCoin).Append(",\"rows\":[");
for (int i = 0; i < plan.Count; i++)
{
var p = plan[i];
if (i > 0) sb.Append(',');
sb.Append('{');
Str(sb, "key", p.Def.Key, first: true);
Str(sb, "label", p.Label);
sb.Append(",\"cur\":").Append(p.Cur).Append(",\"tgt\":").Append(p.Tgt).Append(",\"cap\":").Append(p.Ceiling)
.Append(",\"inc\":").Append(p.Inc);
Str(sb, "lum", p.Lum > 0 ? IltParse.Compact((double)p.Lum) : "-");
sb.Append(",\"coins\":").Append(p.Coins).Append('}');
}
sb.Append(']');
decimal totalLum = plan.Sum(p => p.Lum);
long totalCoins = plan.Sum(p => p.Coins);
long bankCoins = _ctx.State.Bank.EnlightenedCoins;
long lumPerCoin = C.LumPerEnlightenedCoin;
long coinsShort = Math.Max(0, totalCoins - bankCoins);
// Totals row (UB's TOTALS line) and the e-coin summary under the table.
sb.Append(",\"totCur\":").Append(plan.Sum(p => p.Cur))
.Append(",\"totTgt\":").Append(plan.Sum(p => p.Tgt))
.Append(",\"totInc\":").Append(plan.Sum(p => p.Inc))
.Append(",\"totCoins\":").Append(totalCoins);
Str(sb, "totLum", totalLum > 0 ? IltParse.Compact((double)totalLum) : "-");
Str(sb, "coinsLine", $"E-coins needed: {IltParse.N0(totalCoins)} banked: {IltParse.N0(bankCoins)} short: {IltParse.N0(coinsShort)}");
Str(sb, "lumToBuy", coinsShort == 0 ? "Lum to buy e-coins: none needed"
: lumPerCoin > 0 ? $"Lum to buy e-coins: ~{IltParse.Compact((double)coinsShort * lumPerCoin)}"
: "Lum to buy e-coins: set Lum per coin");
// Older engine builds read these three.
Str(sb, "total", $"Total: {IltParse.Compact((double)totalLum)} luminance, {IltParse.N0(totalCoins)} coins");
Str(sb, "short", coinsShort > 0
? $"Coins short: {IltParse.N0(coinsShort)}" + (lumPerCoin > 0 ? $" (~{IltParse.Compact((double)coinsShort * lumPerCoin)} luminance to buy)" : "")
: string.Empty);
Str(sb, "banked", $"Banked luminance: {IltParse.Compact(_ctx.State.Bank.Luminance)}");
Str(sb, "copyDiscord", AugDiscordText(plan));
Str(sb, "copyIngame", AugIngameText(plan));
AppendAugCostJson(sb);
sb.Append('}');
}
/// <summary><c>"cfg":{...}</c>: this world's cost rules for the "Cost settings" editor.</summary>
private void AppendAugCostJson(StringBuilder sb)
{
string world = _ctx.Options.WorldName;
var p = AugProfile;
var inv = System.Globalization.CultureInfo.InvariantCulture;
sb.Append(",\"cfg\":{");
Str(sb, "world", world.Length > 0 ? world : "unknown world", first: true);
sb.Append(",\"custom\":").Append(Bool(AugCosts.IsCustom(world))).Append(",\"mults\":[");
for (int i = 0; i < p.Multipliers.Length; i++)
sb.Append(i > 0 ? "," : "").Append(p.Multipliers[i].ToString("R", inv));
sb.Append("],\"rows\":[");
for (int i = 0; i < p.Augs.Count; i++)
{
var r = p.Augs[i];
if (i > 0) sb.Append(',');
sb.Append('{');
Str(sb, "key", r.Key, first: true);
Str(sb, "label", IltAugCosts.Label(r.Key));
sb.Append(",\"base\":").Append(r.Base)
.Append(",\"pct\":").Append(r.LinearPercent.ToString("R", inv))
.Append(",\"coins\":").Append(r.CoinsPerLevel)
.Append(",\"s1\":").Append(r.S1).Append(",\"s2\":").Append(r.S2)
.Append(",\"s3\":").Append(r.S3).Append(",\"s4\":").Append(r.S4)
.Append(",\"cap\":").Append(r.Cap).Append('}');
}
sb.Append("]}");
}
/// <summary>"augcfg &lt;aug&gt; &lt;field&gt; &lt;value&gt;": one cost-rule edit for this world.</summary>
private void EditAugRule(string key, string field, string value)
{
var inv = System.Globalization.CultureInfo.InvariantCulture;
bool isInt = int.TryParse(value, System.Globalization.NumberStyles.Integer, inv, out int iv);
bool isNum = double.TryParse(value, System.Globalization.NumberStyles.Float, inv, out double dv);
long amount = 0;
bool isAmount = field == "base" && IltParse.TryParseAmount(value, out amount);
if (!isInt && !isNum && !isAmount) return;
AugCosts.Edit(_ctx.Options.WorldName, p =>
{
var r = p.Augs.FirstOrDefault(x => x.Key.Equals(key, StringComparison.OrdinalIgnoreCase));
if (r == null) return;
switch (field)
{
case "base": if (isAmount) r.Base = amount; break;
case "pct": if (isNum) r.LinearPercent = dv; break;
case "coins": if (isInt) r.CoinsPerLevel = iv; break;
case "s1": if (isInt) r.S1 = iv; break;
case "s2": if (isInt) r.S2 = iv; break;
case "s3": if (isInt) r.S3 = iv; break;
case "s4": if (isInt) r.S4 = iv; break;
case "cap": if (isInt) r.Cap = iv; break;
}
});
}
/// <summary>
/// UB's "Copy Discord" table in a code block. ASCII only: the engine reads the snapshot as ANSI.
/// </summary>
private string AugDiscordText(List<AugPlan> plan)
{
string name = string.IsNullOrEmpty(_ctx.CharName) ? "character" : _ctx.CharName;
string rule = new('-', 56);
var t = new StringBuilder();
t.Append("```\n").Append("Augmentations - ").Append(name).Append('\n').Append(rule).Append('\n');
t.Append($"{"Type",-15} {"Current",-8} {"Target",-8} {"Inc",-5} {"Lum Cost",-10} {"Coins",-6}\n").Append(rule).Append('\n');
foreach (var p in plan)
{
if (p.Cur <= 0 && p.Tgt <= 0) continue;
string lum = p.Lum > 0 ? IltParse.Compact((double)p.Lum) : "-";
t.Append($"{p.Label,-15} {p.Cur,-8} {p.Tgt,-8} {p.Inc,-5} {lum,-10} {p.Coins,-6}\n");
}
decimal totalLum = plan.Sum(p => p.Lum);
t.Append(rule).Append('\n');
t.Append($"{"TOTALS:",-15} {plan.Sum(p => p.Cur),-8} {plan.Sum(p => p.Tgt),-8} {plan.Sum(p => p.Inc),-5} "
+ $"{(totalLum > 0 ? IltParse.Compact((double)totalLum) : "-"),-10} {plan.Sum(p => p.Coins),-6}\n");
t.Append("```");
return t.ToString();
}
/// <summary>UB's "Copy In-Game": one line of current levels with short names, for pasting into chat.</summary>
private string AugIngameText(List<AugPlan> plan)
{
string name = string.IsNullOrEmpty(_ctx.CharName) ? "character" : _ctx.CharName;
var parts = plan.Where(p => p.Cur > 0).Select(p => $"{AugShortName(p.Def.Key)}: {IltParse.N0(p.Cur)}").ToList();
return parts.Count == 0
? $"Augmentation Levels - {name}: none loaded"
: $"Augmentation Levels - {name} ({IltParse.N0(plan.Sum(p => p.Cur))} total): {string.Join(", ", parts)}";
}
private static string AugShortName(string key) => key switch
{
"creature" => "Crit",
"duration" => "Dur",
"specialization" => "Spec",
"summon" => "Sum",
"melee" => "Mel",
"missile" => "Mis",
_ => char.ToUpperInvariant(key[0]) + key.Substring(1),
};
private void AppendEnlJson(StringBuilder sb)
{
int enl = _enl;
sb.Append("\"enl\":{\"off\":").Append(Bool(_ctx.Options.IsOff(IltFeature.Enl)));
Str(sb, "header", $"Enlightenment {enl} Level {_level} Unassigned XP {IltParse.Compact(_unassignedXp)}");
var next = EnlStepCost(enl + 1);
Str(sb, "next", $"Next ({enl + 1}): " + (next.Count > 0
? $"{next.Count} {next.Item} (have {HaveFor(next.Wcid)})" + (next.Lum > 0 ? $" + {IltParse.Compact((double)next.Lum)} lum" : "")
: "no materials"));
int target = C.EnlTargetLevel <= enl ? enl + 5 : C.EnlTargetLevel;
sb.Append(",\"enl\":").Append(enl).Append(",\"target\":").Append(target).Append(",\"plan\":[");
var totals = new Dictionary<string, long>();
decimal lumTotal = 0;
for (int t = enl + 1; t <= Math.Max(enl + 1, target) && t <= enl + 500; t++)
{
var s = EnlStepCost(t);
if (s.Count > 0) totals[s.Item] = (totals.TryGetValue(s.Item, out long v) ? v : 0) + s.Count;
lumTotal += s.Lum;
}
bool firstLine = true;
foreach (var kv in totals) { StrItem(sb, $"{IltParse.N0(kv.Value)} {kv.Key}", ref firstLine); }
if (lumTotal > 0)
StrItem(sb, $"{IltParse.Compact((double)lumTotal)} luminance (banked {IltParse.Compact(_ctx.State.Bank.Luminance)})", ref firstLine);
sb.Append(']');
int coinsPerToken = C.EnlightenedCoinsPerToken;
sb.Append(",\"coinsPerToken\":").Append(coinsPerToken);
string tokensShort = string.Empty;
if (totals.TryGetValue("Enlightenment Tokens", out long tokNeed) && coinsPerToken > 0)
{
long shortTok = Math.Max(0, tokNeed - _enlHave[0]);
if (shortTok > 0) tokensShort = $"Tokens short: {shortTok} (~{IltParse.N0(shortTok * coinsPerToken)} coins)";
}
Str(sb, "tokensShort", tokensShort);
AppendEnlCalculatorJson(sb, enl, target, totals, lumTotal);
var blockers = NextEnlBlockers();
sb.Append(",\"blockers\":[");
bool firstBlocker = true;
foreach (string b in blockers) StrItem(sb, b, ref firstBlocker);
sb.Append(']');
Str(sb, "serverChecks", $"Server also checks: not in a dungeon, free pack slots ({(_freeSlots >= 0 ? _freeSlots.ToString() : "?")} free), "
+ "all luminance augs (past 10), society master (past 30).");
sb.Append(",\"auto\":").Append(Bool(C.AutoEnlightenEnabled))
.Append(",\"armed\":").Append(Bool(_autoArmed))
.Append(",\"spendFirst\":").Append(Bool(C.AutoEnlightenSpendXpFirst))
.Append(",\"checkEvery\":").Append(C.AutoEnlightenCheckSeconds);
Str(sb, "status", _enlStatus);
sb.Append('}');
}
/// <summary>Per-level rows the calculator lists at most (a bigger range is summarised in the totals).</summary>
private const int EnlLevelRowsMax = 100;
/// <summary>
/// UB-IT's Enlighten calculator: per-level table (green while stock lasts, the sigil chain counted),
/// material summary (still need / have), the 301-325 sigil chain, and the e-coin line shared with
/// token conversion. Appends "levels", "materials", "chain", "chainNote", "ecoins", "ecoinsLum".
/// </summary>
private void AppendEnlCalculatorJson(StringBuilder sb, int enl, int target, Dictionary<string, long> totals, decimal lumTotal)
{
// Simulated stock: tokens, medallions, crests on hand, sigils via the chain, banked luminance.
long tok = _enlHave[0], med = _enlHave[1], crest = _enlHave[3];
decimal lum = (decimal)_ctx.State.Bank.Luminance;
var chain = _chain.Clone();
long sigilCraftable = IltSigilChain.Fulfillable(chain);
sb.Append(",\"levels\":[");
int last = Math.Min(Math.Max(enl + 1, target), enl + EnlLevelRowsMax);
for (int t = enl + 1; t <= last; t++)
{
var s = EnlStepCost(t);
bool ok = lum >= s.Lum;
if (ok && s.Count > 0)
{
switch (s.Wcid)
{
case IltInventory.WcidEnlToken: ok = tok >= s.Count; if (ok) tok -= s.Count; break;
case IltInventory.WcidEnlMedallion: ok = med >= s.Count; if (ok) med -= s.Count; break;
case IltInventory.WcidEnlSigil: ok = sigilCraftable >= s.Count; if (ok) sigilCraftable -= s.Count; break;
default: ok = crest >= s.Count; if (ok) crest -= s.Count; break;
}
}
if (ok) lum -= s.Lum;
if (t > enl + 1) sb.Append(',');
sb.Append("{\"t\":").Append(t);
Str(sb, "item", ShortItem(s.Item));
sb.Append(",\"count\":").Append(s.Count);
Str(sb, "lum", s.Lum > 0 ? IltParse.Compact((double)s.Lum) : "-");
sb.Append(",\"ok\":").Append(Bool(ok)).Append('}');
}
sb.Append(']');
// Material summary: Still need = demand minus what is on hand.
long sigilsNeed = totals.TryGetValue("Enlightenment Sigils", out long sn) ? sn : 0;
var shortfall = IltSigilChain.Shortfall(sigilsNeed, _chain);
decimal bankLum = (decimal)_ctx.State.Bank.Luminance;
sb.Append(",\"materials\":[");
bool firstMat = true;
void Mat(string label, string need, string have, bool ok)
{
if (!firstMat) sb.Append(',');
firstMat = false;
sb.Append('{');
Str(sb, "label", label, first: true);
Str(sb, "need", need);
Str(sb, "have", have);
sb.Append(",\"ok\":").Append(Bool(ok)).Append('}');
}
if (lumTotal > 0)
{
decimal lumStill = Math.Max(0, lumTotal - bankLum);
Mat("Luminance", lumStill > 0 ? IltParse.Compact((double)lumStill) : "0", IltParse.Compact((double)bankLum), lumStill == 0);
}
void Item(string key, string label, long have, bool extraOk = false)
{
if (!totals.TryGetValue(key, out long need)) return;
long still = Math.Max(0, need - have);
Mat(label, IltParse.N0(still), IltParse.N0(have), still == 0 || extraOk);
}
Item("Enlightenment Tokens", "Tokens", _enlHave[0]);
Item("Enlightenment Medallions", "Medallions", _enlHave[1]);
Item("Enlightenment Sigils", "Sigils", _enlHave[2], extraOk: shortfall.Covered);
Item("Enlightenment Crests", "Crests", _enlHave[3]);
sb.Append(']');
// Sigil chain rows (only when the plan reaches 301-325).
sb.Append(",\"chain\":[");
if (sigilsNeed > 0)
{
bool firstRow = true;
void Row(string label, long need, long have, bool ok, bool craft)
{
if (!firstRow) sb.Append(',');
firstRow = false;
sb.Append('{');
Str(sb, "label", label, first: true);
sb.Append(",\"need\":").Append(need).Append(",\"have\":").Append(have)
.Append(",\"ok\":").Append(Bool(ok)).Append(",\"craft\":").Append(Bool(craft)).Append('}');
}
Row("Ascension Coins", shortfall.AscensionToCraft, _chain.AscensionCoins,
shortfall.AscensionToCraft == 0 || (shortfall.CoinsShort == 0 && shortfall.TrinketsShort == 0), true);
Row("Lifeblood Elixirs", shortfall.ElixirsToCraft, _chain.LifebloodElixirs,
shortfall.ElixirsToCraft == 0 || (shortfall.ExtractsShort == 0 && shortfall.SplittersShort == 0 && shortfall.PlantsShort == 0), true);
Row("Lifebloom Resins", shortfall.ResinsToCraft, _chain.LifebloomResins,
shortfall.ResinsToCraft == 0 || (shortfall.SplittersShort == 0 && shortfall.PlantsShort == 0), true);
Row("E-coins", shortfall.CoinsShort, _chain.EnlightenedCoins, shortfall.CoinsShort == 0, false);
Row("Ancient Yalani Trinkets", shortfall.TrinketsShort, _chain.YalaniTrinkets, shortfall.TrinketsShort == 0, false);
Row("Necrolytic Extracts", shortfall.ExtractsShort, _chain.NecrolyticExtracts, shortfall.ExtractsShort == 0, false);
Row("Life Splitters", shortfall.SplittersShort, _chain.LifeSplitters, shortfall.SplittersShort == 0, false);
Row("Plants", shortfall.PlantsShort, _chain.Plants, shortfall.PlantsShort == 0, false);
}
sb.Append(']');
Str(sb, "chainNote", sigilsNeed > 0
? $"Sigil = Lifeblood Elixir + Ascension Coin. {IltParse.N0(shortfall.SigilsToCraft)} to craft; "
+ (shortfall.Covered ? "the chain covers them." : "Need = crafts left (in-between items) or mats to get (raw items).")
: string.Empty);
// E-coins: Ascension Coin crafts first, then token conversion at the shop price.
long tokNeed = totals.TryGetValue("Enlightenment Tokens", out long tn) ? tn : 0;
IltSigilChain.EcoinDemand(_chain.EnlightenedCoins, shortfall.CoinsForCraft, Math.Max(0, tokNeed - _enlHave[0]),
C.EnlightenedCoinsPerToken, out _, out long tokensStill, out long coinsNeeded);
Str(sb, "ecoins", tokNeed > 0 || shortfall.CoinsForCraft > 0
? $"E-coins needed: {IltParse.N0(coinsNeeded)} have {IltParse.N0(_chain.EnlightenedCoins)} (bank + pack)"
+ (shortfall.CoinsForCraft > 0 ? $" Ascension Coins use {IltParse.N0(shortfall.CoinsForCraft)}" : "")
+ (tokensStill > 0 ? $" tokens still {IltParse.N0(tokensStill)}" : "")
: string.Empty);
long lumPerCoin = C.LumPerEnlightenedCoin;
Str(sb, "ecoinsLum", coinsNeeded <= 0 ? string.Empty
: lumPerCoin > 0 ? $"Lum to buy e-coins: ~{IltParse.Compact((double)coinsNeeded * lumPerCoin)}"
: "Lum to buy e-coins: set Lum per e-coin (Augmentations)");
}
/// <summary>Short label for the per-level table's item column.</summary>
private static string ShortItem(string item) => item switch
{
"Enlightenment Tokens" => "Tokens",
"Enlightenment Medallions" => "Medallions",
"Enlightenment Sigils" => "Sigils",
"Enlightenment Crests" => "Crests",
_ => "-",
};
private static string Bool(bool b) => b ? "true" : "false";
private static void Str(StringBuilder sb, string name, string value, bool first = false)
{
if (!first) sb.Append(',');
sb.Append('"').Append(name).Append("\":\"").Append(RynthAiPlugin.JsonEscape(value ?? string.Empty)).Append('"');
}
private static void StrItem(StringBuilder sb, string value, ref bool first)
{
if (!first) sb.Append(',');
first = false;
sb.Append('"').Append(RynthAiPlugin.JsonEscape(value)).Append('"');
}
/// <summary>
/// "prog" remote command from the engine Skills panel. Pump thread. The panel asks its own
/// confirmation before "enlighten" and "autoenl on|arm", so none is asked here.
/// </summary>
public void HandleRemote(string[] a)
{
if (a.Length == 0) return;
RynthLog.Trace(LogCat.IltProgression, $"HandleRemote({string.Join(" ", a)})");
string arg1 = a.Length > 1 ? a[1] : string.Empty;
int.TryParse(a.Length > 2 ? a[2] : arg1, out int n);
string verb = a[0].ToLowerInvariant();
if (verb.StartsWith("attr", StringComparison.Ordinal) && Attributes.HandleRemote(verb, a)) return;
switch (verb)
{
case "augload": RequestAugs(); break;
case "augreset":
// UB's "Reset Target": every target back to the current level.
lock (_augLevels)
foreach (var (key, _) in IltAugCosts.Labels)
C.AugTargets[key] = _augLevels.TryGetValue(key, out int c) ? c : 0;
break;
case "augtarget" when a.Length > 2:
foreach (var def in AugProfile.Augs)
{
if (!def.Key.Equals(arg1, StringComparison.OrdinalIgnoreCase)) continue;
int cur;
lock (_augLevels) cur = _augLevels.TryGetValue(def.Key, out int c) ? c : 0;
C.AugTargets[def.Key] = Math.Clamp(n, 0, IltAugCosts.Ceiling(def, cur));
break;
}
break;
case "augmult" when a.Length > 2:
// "augmult <tier 0-4> <multiplier>": tier 0 is below S1, tier 4 is from S4 on.
if (int.TryParse(arg1, out int tier) && tier is >= 0 and <= 4
&& double.TryParse(a[2], System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out double mult))
AugCosts.Edit(_ctx.Options.WorldName, p => p.Multipliers[tier] = mult);
break;
case "augcfg" when a.Length > 3:
EditAugRule(arg1, a[2].ToLowerInvariant(), a[3]);
break;
case "augcfgreset":
AugCosts.Reset(_ctx.Options.WorldName);
break;
case "lumpercoin":
if (IltParse.TryParseAmount(arg1, out long lpc)) C.LumPerEnlightenedCoin = Math.Max(0, lpc);
break;
case "enltarget": C.EnlTargetLevel = Math.Max(_enl + 1, n); break;
case "coinspertoken": C.EnlightenedCoinsPerToken = Math.Max(0, n); break;
case "enlighten": SendEnlighten("manual, Skills panel"); break;
case "autoenl":
switch (arg1.ToLowerInvariant())
{
case "on":
C.AutoEnlightenEnabled = true;
_autoArmed = true;
_ctx.Chat("[Mini Remote] Auto-enlighten armed for this session.");
break;
case "arm": if (C.AutoEnlightenEnabled) _autoArmed = true; break;
default: C.AutoEnlightenEnabled = false; _autoArmed = false; break;
}
break;
case "spendfirst": C.AutoEnlightenSpendXpFirst = arg1.Equals("on", StringComparison.OrdinalIgnoreCase); break;
case "checkevery": C.AutoEnlightenCheckSeconds = Math.Max(10, n); break;
}
}
}

View file

@ -0,0 +1,456 @@
// IltQuests.cs — Quest Tracker UI and Quest Bonus (/qb) list for the ILT Hub Character tab.
//
// Quest Tracker reuses the meta QuestTracker (the same /myquests cache the meta
// expression engine reads) — it never runs a second parser. Friendly names come from:
// 1. an optional user-supplied quests.xml (<SuiteDir>\RynthAi\quests.xml),
// 2. the description the server prints in /myquests,
// 3. the raw flag key.
// UB's bundled quests.xml is NOT embedded (no license on UB content).
//
// QB: "/qb list" prints a completed and an incomplete section; both are tracked
// separately (UB merged them). Server throttles /qb to once per minute.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Numerics;
using System.Text.RegularExpressions;
using System.Xml;
using ImGuiNET;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.Plugin.RynthAi.Meta;
using RynthCore.Install;
namespace RynthCore.Plugin.RynthAi.IltHub;
internal sealed class IltQuests : IIltFeature
{
/// <summary>Optional user quest-name file (UB-style or simple key/name XML).</summary>
public static readonly string QuestsXmlPath = System.IO.Path.Combine(RynthInstallPaths.RynthAiDir, @"quests.xml");
private static readonly Regex KillTaskRegex = new(@"(killtask|killcount|slayerquest|totalgolem.*dead|(kills$))",
RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
private static readonly Regex QbFlagLine = new(@"^[a-zA-Z0-9_\-!@\(\)?]+$", RegexOptions.Compiled | RegexOptions.CultureInvariant);
private const long QuestRefreshCooldownMs = 60_000;
private const long QbCooldownMs = 60_000;
private readonly IltHubContext _ctx;
private readonly Func<QuestTracker?> _tracker;
private Dictionary<string, string> _friendlyNames = new(StringComparer.OrdinalIgnoreCase);
private long _lastQuestRefreshAt = -QuestRefreshCooldownMs;
private long _lastQbAt = -QbCooldownMs;
// QB results (replaced wholesale; read by the render thread).
private volatile string[] _qbCompleted = Array.Empty<string>();
private volatile string[] _qbIncomplete = Array.Empty<string>();
private volatile string _qbStatus = "not loaded";
private long _qbCount = -1;
private volatile int _qbGeneration; // bumped per successful "/qb list"; 0 = never loaded this session
// Render-thread UI state.
private int _questView; // 0 timed, 1 kill tasks, 2 once, 3 all
public IltQuests(IltHubContext ctx, Func<QuestTracker?> tracker)
{
_ctx = ctx;
_tracker = tracker;
LoadFriendlyNames();
}
public enum QuestKind { Timed, KillTask, Once }
public static QuestKind Classify(QuestRecord r)
{
if (KillTaskRegex.IsMatch(r.Key) && r.MaxSolves >= 0) return QuestKind.KillTask;
if (r.MaxSolves == 1 && r.Solves <= 1) return QuestKind.Once;
return QuestKind.Timed;
}
public string FriendlyName(QuestRecord r)
{
if (_friendlyNames.TryGetValue(r.Key, out string? n) && !string.IsNullOrWhiteSpace(n)) return n;
if (!string.IsNullOrWhiteSpace(r.Description)) return r.Description;
return r.Key;
}
// ── quests.xml (optional) ───────────────────────────────────────────────
/// <summary>Reads any element carrying a key/flag attribute plus a name/description.</summary>
public void LoadFriendlyNames()
{
var map = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
try
{
if (File.Exists(QuestsXmlPath))
{
using var reader = XmlReader.Create(QuestsXmlPath, new XmlReaderSettings { DtdProcessing = DtdProcessing.Ignore, IgnoreComments = true });
while (reader.Read())
{
if (reader.NodeType != XmlNodeType.Element || !reader.HasAttributes) continue;
string? key = null, name = null;
while (reader.MoveToNextAttribute())
{
string a = reader.Name.ToLowerInvariant();
if (a is "key" or "flag" or "questflag" or "id") key = reader.Value;
else if (a is "name" or "description" or "title" or "friendlyname") name ??= reader.Value;
}
reader.MoveToElement();
if (!string.IsNullOrWhiteSpace(key) && !string.IsNullOrWhiteSpace(name))
map[key.Trim().ToLowerInvariant()] = name.Trim();
}
}
}
catch (Exception ex) { RynthLog.Exception(LogCat.IltQuests, ex, "quests.xml load"); }
_friendlyNames = map;
}
// ── Commands ────────────────────────────────────────────────────────────
/// <summary>Quiet /myquests refresh with a 60 s client-side cooldown (server throttle).</summary>
public string RefreshQuests()
{
RynthLog.Trace(LogCat.IltQuests, $"RefreshQuests()");
var t = _tracker();
if (t == null) return "Quest tracker not ready.";
if (_ctx.Options.IsOff(IltFeature.Quests) || t.Disabled) return "/myquests is disabled on this server.";
long now = IltHubContext.NowMs;
if (now - _lastQuestRefreshAt < QuestRefreshCooldownMs)
return $"Wait {(QuestRefreshCooldownMs - (now - _lastQuestRefreshAt)) / 1000}s (server allows one /myquests per minute).";
_lastQuestRefreshAt = now;
t.Refresh(quiet: true);
return "Refreshing quests...";
}
/// <summary>"/ra quests check &lt;regex&gt;" — lists up to 5 matching flags in chat.</summary>
public void CheckCommand(string pattern)
{
var t = _tracker();
if (t == null) { _ctx.Chat("[Mini Remote] Quest tracker not ready."); return; }
Regex rx;
try { rx = new Regex(pattern, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant, TimeSpan.FromMilliseconds(200)); }
catch (ArgumentException ex) { _ctx.Chat("[Mini Remote] Bad pattern: " + ex.Message); return; }
var hits = t.Snapshot().Where(r => rx.IsMatch(r.Key) || rx.IsMatch(FriendlyName(r))).OrderBy(r => r.Key).ToList();
if (hits.Count == 0) { _ctx.Chat($"[Mini Remote] No quest flags match '{pattern}' ({t.Count} cached)."); return; }
foreach (var r in hits.Take(5))
_ctx.Chat($"[Mini Remote] {FriendlyName(r)} [{r.Key}] solves {r.Solves}{(r.MaxSolves > 0 ? "/" + r.MaxSolves : "")} - {IltParse.Duration(r.TimeUntilReady())}");
if (hits.Count > 5) _ctx.Chat($"[Mini Remote] ...and {hits.Count - 5} more.");
}
/// <summary>Captures "/qb list" (quiet).</summary>
public string RefreshQb()
{
RynthLog.Trace(LogCat.IltQuests, $"RefreshQb()");
if (_ctx.Options.IsOff(IltFeature.Qb)) return "/qb is disabled on this server.";
long now = IltHubContext.NowMs;
if (now - _lastQbAt < QbCooldownMs)
return $"Wait {(QbCooldownMs - (now - _lastQbAt)) / 1000}s (server allows one /qb per minute).";
if (_ctx.Capture.IsPending("/qb list")) return "Already loading...";
_lastQbAt = now;
_qbStatus = "loading...";
_ctx.Capture.Enqueue(new IltChatRequest
{
Command = "/qb list",
IsResponseLine = IsQbLine,
IsTerminator = t => t.Contains("Quest bonus list is empty", StringComparison.OrdinalIgnoreCase)
|| t.Contains("\"qb\" is not currently enabled", StringComparison.OrdinalIgnoreCase)
|| t.StartsWith("[QB] This command may only be run once every", StringComparison.OrdinalIgnoreCase),
IdleEndMs = 5000,
FirstLineTimeoutMs = 30000,
Eat = true,
OnComplete = OnQbResult,
});
return "Loading quest bonus list...";
}
private static bool IsQbLine(string t)
{
if (t.StartsWith("Your completed quest bonus list", StringComparison.OrdinalIgnoreCase)
|| t.StartsWith("Your incomplete quest bonus list", StringComparison.OrdinalIgnoreCase)
|| t.StartsWith("Your current quest bonus count", StringComparison.OrdinalIgnoreCase))
return true;
if (!QbFlagLine.IsMatch(t)) return false;
if (t.StartsWith("You ", StringComparison.Ordinal) || t.StartsWith("The ", StringComparison.Ordinal)) return false;
return !(t.Contains("You have", StringComparison.OrdinalIgnoreCase) || t.Contains("command", StringComparison.OrdinalIgnoreCase)
|| t.Contains("enabled", StringComparison.OrdinalIgnoreCase) || t.Contains("list", StringComparison.OrdinalIgnoreCase));
}
private void OnQbResult(IltChatResult r)
{
if (r.UnknownCommand) { _ctx.Options.Set(IltFeature.Qb, IltTri.Off); _qbStatus = "/qb not available"; return; }
if (r.TerminatorLine != null)
{
if (r.TerminatorLine.Contains("not currently enabled", StringComparison.OrdinalIgnoreCase))
{ _ctx.Options.Set(IltFeature.Qb, IltTri.Off); _qbStatus = "/qb is disabled on this server"; return; }
if (r.TerminatorLine.Contains("only be run once", StringComparison.OrdinalIgnoreCase))
{ _qbStatus = "rate limited by the server"; return; }
}
if (r.TimedOut) { _qbStatus = "no reply from server"; return; }
_ctx.Options.Set(IltFeature.Qb, IltTri.On);
var done = new List<string>();
var todo = new List<string>();
List<string>? current = null;
foreach (string line in r.Lines)
{
if (line.StartsWith("Your completed quest bonus list", StringComparison.OrdinalIgnoreCase)) { current = done; continue; }
if (line.StartsWith("Your incomplete quest bonus list", StringComparison.OrdinalIgnoreCase)) { current = todo; continue; }
if (line.StartsWith("Your current quest bonus count", StringComparison.OrdinalIgnoreCase))
{
int colon = line.IndexOf(':');
if (colon > 0) _qbCount = IltParse.ParseLeadingLong(line.Substring(colon + 1));
continue;
}
if (line.Contains("is empty", StringComparison.OrdinalIgnoreCase)) continue;
(current ?? done).Add(line.Trim());
}
done.Sort(StringComparer.OrdinalIgnoreCase);
todo.Sort(StringComparer.OrdinalIgnoreCase);
_qbCompleted = done.ToArray();
_qbIncomplete = todo.ToArray();
_qbStatus = $"{done.Count} completed, {todo.Count} incomplete";
_qbGeneration++;
}
/// <summary>Increments each time a "/qb list" reply is parsed (0 = not loaded this session).</summary>
public int QbGeneration => _qbGeneration;
/// <summary>True when the last "/qb list" (completed or incomplete) contains the flag.</summary>
public bool QbHasFlag(string flag)
{
if (string.IsNullOrWhiteSpace(flag)) return false;
foreach (string f in _qbCompleted)
if (f.Equals(flag, StringComparison.OrdinalIgnoreCase)) return true;
foreach (string f in _qbIncomplete)
if (f.Equals(flag, StringComparison.OrdinalIgnoreCase)) return true;
return false;
}
/// <summary>Login probe tap: "/qb" (no args) prints the count line.</summary>
public void ApplyQbProbe(List<string> lines)
{
RynthLog.Trace(LogCat.IltQuests, $"ApplyQbProbe(lines={lines.Count})");
foreach (string line in lines)
if (line.StartsWith("Your current quest bonus count", StringComparison.OrdinalIgnoreCase))
{
int colon = line.IndexOf(':');
if (colon > 0) _qbCount = IltParse.ParseLeadingLong(line.Substring(colon + 1));
}
}
// ── IIltFeature ─────────────────────────────────────────────────────────
public void Tick(long nowMs) { }
public bool OnChat(string text) => false;
public void OnLogout()
{
_qbCompleted = Array.Empty<string>();
_qbIncomplete = Array.Empty<string>();
_qbCount = -1;
_qbStatus = "not loaded";
_qbGeneration = 0;
}
// ── UI (render thread) ──────────────────────────────────────────────────
/// <summary>Quest tracker body, filling the Mini Remote's Quests tab (the table uses the remaining height).</summary>
public void RenderQuestTracker()
{
var t = _tracker();
if (t == null) { ImGui.TextDisabled("Quest tracker not ready."); return; }
if (_ctx.Options.IsOff(IltFeature.Quests) || t.Disabled)
{
ImGui.TextColored(LegacyDashboardRenderer.ColTextMute, "/myquests is disabled on this server.");
return;
}
var cs = _ctx.State.Character;
if (ImGui.SmallButton("Refresh##quests")) _ctx.Post(() => _ctx.Chat("[Mini Remote] " + RefreshQuests()));
ImGui.SameLine();
if (ImGui.SmallButton("Reload quests.xml")) _ctx.Post(LoadFriendlyNames);
ImGui.SameLine();
ImGui.TextDisabled(t.IsRefreshing ? "refreshing..." : t.LastStatus
+ (t.LastRefreshUtc == DateTime.MinValue ? "" : " @ " + t.LastRefreshUtc.ToLocalTime().ToString("t")));
string filter = cs.QuestFilter;
ImGui.SetNextItemWidth(220);
if (ImGui.InputTextWithHint("##qfilter", "filter by name or key", ref filter, 64u))
cs.QuestFilter = filter;
ImGui.SameLine();
ImGui.RadioButton("Timed", ref _questView, 0); ImGui.SameLine();
ImGui.RadioButton("Kill tasks", ref _questView, 1); ImGui.SameLine();
ImGui.RadioButton("Once", ref _questView, 2); ImGui.SameLine();
ImGui.RadioButton("All", ref _questView, 3);
bool favOnly = cs.QuestFavoritesOnly;
if (ImGui.Checkbox("Favorites only", ref favOnly)) cs.QuestFavoritesOnly = favOnly;
ImGui.SameLine();
bool favHud = cs.ShowQuestFavoritesHud;
if (ImGui.Checkbox("Show floating favorites HUD", ref favHud)) cs.ShowQuestFavoritesHud = favHud;
ImGui.SameLine();
ImGui.TextDisabled("(click * to star a quest)");
var favorites = FavoriteSet();
var rows = t.Snapshot()
.Where(r => favOnly ? favorites.Contains(r.Key) : _questView == 3 || (int)Classify(r) == ViewToKind(_questView))
.Where(r => filter.Length == 0 || r.Key.Contains(filter, StringComparison.OrdinalIgnoreCase)
|| FriendlyName(r).Contains(filter, StringComparison.OrdinalIgnoreCase))
.OrderBy(r => r.TimeUntilReady())
.ThenBy(r => FriendlyName(r), StringComparer.OrdinalIgnoreCase)
.ToArray();
if (ImGui.BeginTable("##iltquests", 5, ImGuiTableFlags.RowBg | ImGuiTableFlags.ScrollY | ImGuiTableFlags.BordersInnerV | ImGuiTableFlags.Resizable,
new Vector2(0, -1)))
{
ImGui.TableSetupScrollFreeze(0, 1);
ImGui.TableSetupColumn("*", ImGuiTableColumnFlags.WidthFixed, 18);
ImGui.TableSetupColumn("Quest");
ImGui.TableSetupColumn("Solves", ImGuiTableColumnFlags.WidthFixed, 70);
ImGui.TableSetupColumn("Ready", ImGuiTableColumnFlags.WidthFixed, 110);
ImGui.TableSetupColumn("Key");
ImGui.TableHeadersRow();
foreach (var r in rows)
{
ImGui.TableNextRow();
ImGui.TableNextColumn();
bool starred = favorites.Contains(r.Key);
ImGui.PushStyleColor(ImGuiCol.Text, starred ? FavStarOn : FavStarOff);
if (ImGui.Selectable($"*##fav{r.Key}", false))
{
string key = r.Key;
_ctx.Post(() => ToggleFavorite(key));
}
ImGui.PopStyleColor();
if (ImGui.IsItemHovered()) ImGui.SetTooltip(starred ? "Remove from favorites" : "Add to favorites");
ImGui.TableNextColumn(); ImGui.TextUnformatted(FriendlyName(r));
ImGui.TableNextColumn(); ImGui.TextUnformatted(r.MaxSolves > 0 ? $"{r.Solves}/{r.MaxSolves}" : r.Solves.ToString());
ImGui.TableNextColumn();
var left = r.TimeUntilReady();
if (Classify(r) == QuestKind.Once) ImGui.TextDisabled("done");
else if (left <= TimeSpan.Zero) ImGui.TextColored(LegacyDashboardRenderer.ColGreen, "ready");
else ImGui.TextUnformatted(IltParse.Duration(left));
ImGui.TableNextColumn(); ImGui.TextDisabled(r.Key);
}
ImGui.EndTable();
}
}
private static int ViewToKind(int view) => view switch { 0 => (int)QuestKind.Timed, 1 => (int)QuestKind.KillTask, _ => (int)QuestKind.Once };
// ── Favorites / the Quests tab ──────────────────────────────────────────
private static readonly Vector4 FavStarOn = new(1.00f, 0.82f, 0.25f, 1f);
private static readonly Vector4 FavStarOff = new(0.45f, 0.48f, 0.52f, 1f);
private const string FavHudPopup = "##questfavhudopts";
/// <summary>Starred keys as a set (render thread; the list itself is only edited on the pump thread).</summary>
private HashSet<string> FavoriteSet()
=> new(_ctx.State.Character.QuestFavorites.ToArray(), StringComparer.OrdinalIgnoreCase);
/// <summary>Stars / unstars a quest flag (pump thread).</summary>
private void ToggleFavorite(string key)
{
var list = _ctx.State.Character.QuestFavorites;
if (list.RemoveAll(k => k.Equals(key, StringComparison.OrdinalIgnoreCase)) == 0)
list.Add(key.ToLowerInvariant());
}
/// <summary>The floating favorites HUD (the tracker itself is the Mini Remote's Quests tab). Called every frame.</summary>
public void RenderFloatingWindows()
{
var cs = _ctx.State.Character;
if (cs.ShowQuestFavoritesHud) RenderFavoritesHud(cs);
}
/// <summary>The Mini Remote's Quests tab: the quest bonus (collapsed), then the tracker filling the rest.</summary>
public void RenderTab()
{
// The tab is universal (/myquests); the quest bonus list (/qb) is ILT's.
if (_ctx.Options.IsIltLikeWorld && ImGui.CollapsingHeader("Quest bonus (/qb)##qbwin")) RenderQb();
RenderQuestTracker();
}
/// <summary>Compact always-on list of starred quests and when each is ready.</summary>
private void RenderFavoritesHud(IltCharacterState cs)
{
var flags = ImGuiWindowFlags.NoTitleBar | ImGuiWindowFlags.AlwaysAutoResize | ImGuiWindowFlags.NoScrollbar
| ImGuiWindowFlags.NoFocusOnAppearing | ImGuiWindowFlags.NoNav;
if (cs.QuestFavoritesHudLocked) flags |= ImGuiWindowFlags.NoMove;
ImGui.SetNextWindowPos(new Vector2(260, 120), ImGuiCond.FirstUseEver);
ImGui.SetNextWindowBgAlpha(0.55f);
if (!ImGui.Begin("Quest favorites##iltquestfavhud", flags)) { ImGui.End(); return; }
ImGui.TextColored(LegacyDashboardRenderer.ColTeal, "Quest favorites");
var t = _tracker();
var favorites = FavoriteSet();
if (t == null || favorites.Count == 0)
{
ImGui.TextDisabled(t == null ? "Quest tracker not ready." : "No favorites yet - star quests in the tracker.");
}
else
{
var rows = t.Snapshot().Where(r => favorites.Contains(r.Key))
.OrderBy(r => r.TimeUntilReady()).ThenBy(r => FriendlyName(r), StringComparer.OrdinalIgnoreCase).ToArray();
if (rows.Length == 0) ImGui.TextDisabled("Starred quests not in /myquests yet.");
if (ImGui.BeginTable("##questfavrows", 2, ImGuiTableFlags.SizingFixedFit))
{
foreach (var r in rows)
{
ImGui.TableNextRow();
ImGui.TableNextColumn(); ImGui.TextUnformatted(FriendlyName(r));
ImGui.TableNextColumn();
var left = r.TimeUntilReady();
if (Classify(r) == QuestKind.Once) ImGui.TextDisabled("done");
else if (left <= TimeSpan.Zero) ImGui.TextColored(LegacyDashboardRenderer.ColGreen, "ready");
else ImGui.TextUnformatted(IltParse.Duration(left));
}
ImGui.EndTable();
}
}
if (ImGui.IsWindowHovered() && ImGui.IsMouseReleased(ImGuiMouseButton.Right)) ImGui.OpenPopup(FavHudPopup);
if (ImGui.BeginPopup(FavHudPopup))
{
bool locked = cs.QuestFavoritesHudLocked;
if (ImGui.Checkbox("Lock position", ref locked)) cs.QuestFavoritesHudLocked = locked;
if (ImGui.MenuItem("Open quest tracker")) _ctx.ShowTab?.Invoke(IltSection.Quests);
if (ImGui.MenuItem("Refresh /myquests")) _ctx.Post(() => _ctx.Chat("[Mini Remote] " + RefreshQuests()));
if (ImGui.MenuItem("Hide favorites HUD")) cs.ShowQuestFavoritesHud = false;
ImGui.EndPopup();
}
ImGui.End();
}
public void RenderQb()
{
if (_ctx.Options.IsOff(IltFeature.Qb))
{
ImGui.TextColored(LegacyDashboardRenderer.ColTextMute, "/qb is disabled on this server.");
return;
}
if (ImGui.SmallButton("Load /qb list")) _ctx.Post(() => _ctx.Chat("[Mini Remote] " + RefreshQb()));
ImGui.SameLine();
long count = _qbCount;
ImGui.TextDisabled((count >= 0 ? $"QB count {IltParse.N0(count)} - " : "") + _qbStatus);
string filter = _ctx.State.Character.QbFilter;
ImGui.SetNextItemWidth(220);
if (ImGui.InputTextWithHint("##qbfilter", "filter flags", ref filter, 64u))
_ctx.State.Character.QbFilter = filter;
RenderQbList("Incomplete", _qbIncomplete, filter, LegacyDashboardRenderer.ColAmber);
RenderQbList("Completed", _qbCompleted, filter, LegacyDashboardRenderer.ColGreen);
}
private static void RenderQbList(string label, string[] items, string filter, Vector4 color)
{
var shown = filter.Length == 0 ? items : items.Where(i => i.Contains(filter, StringComparison.OrdinalIgnoreCase)).ToArray();
if (ImGui.TreeNode($"{label} ({shown.Length})##qb{label}"))
{
if (ImGui.SmallButton($"Copy##qbc{label}")) ImGui.SetClipboardText(string.Join(Environment.NewLine, shown));
foreach (string s in shown) ImGui.TextColored(color, s);
ImGui.TreePop();
}
}
}

View file

@ -0,0 +1,104 @@
// IltSections.cs - The Mini Remote's tabs and the Guardian panel. Quests and Pets are universal
// tabs (every server: /myquests and summoning essences aren't ILT's); Character, Banking, Gear,
// Charms and Games are Infinite Leaftide tabs. All are picked from the Mini Remote's tab bar (MiniRemoteHud)
// or "/ra hub open <section>". Guardian is ILT only and a RynthCore ILT panel instead (the bar's
// ILT button, next to Bounties; "/rc guardian"), drawn by this plugin through
// RynthPluginRenderEmbed("guardian").
using System;
namespace RynthCore.Plugin.RynthAi.IltHub;
/// <summary>ILT sections: the Mini Remote's tabs, then the Guardian panel.</summary>
internal enum IltSection
{
Character,
Quests,
Pet,
Banking,
Gear,
Games,
/// <summary>Registry charms (acquired / status / tier / server) and the Guardian Hand.</summary>
Charms,
// Keep Guardian last: MiniRemoteHud sizes its per-tab tables by it.
Guardian,
}
internal static class IltSections
{
/// <summary>
/// The Mini Remote's tabs, in tab-bar order (after its own Remote tab): the universal ones
/// first, then the Infinite Leaftide ones.
/// </summary>
public static readonly IltSection[] Tabs =
{
IltSection.Quests, IltSection.Pet,
IltSection.Character, IltSection.Banking, IltSection.Gear, IltSection.Charms, IltSection.Games,
};
/// <summary>
/// True for the tabs every server gets (Quests, Pets); the rest are Infinite Leaftide's and
/// show only on an ILT world (or with the Force-ILT override).
/// </summary>
public static bool IsUniversal(IltSection s) => s is IltSection.Quests or IltSection.Pet;
/// <summary>The Mini Remote's own tab (the remote itself): its tab id.</summary>
public const string RemoteTab = "";
public static string Label(IltSection s) => s switch
{
IltSection.Character => "Character",
IltSection.Quests => "Quests",
IltSection.Pet => "Pets",
IltSection.Banking => "Banking",
IltSection.Gear => "Gear",
IltSection.Games => "Games",
IltSection.Charms => "Charms",
IltSection.Guardian => "Guardian",
_ => s.ToString(),
};
/// <summary>
/// The section's tab id: saved as HudState.MiniRemoteTab and sent by the engine's dashboard
/// ("/ra hub tab &lt;id&gt;"). TryParse reads it back.
/// </summary>
public static string TabId(IltSection s) => s switch
{
IltSection.Character => "character",
IltSection.Quests => "quests",
IltSection.Pet => "pets",
IltSection.Banking => "banking",
IltSection.Gear => "gear",
IltSection.Games => "games",
IltSection.Charms => "charms",
IltSection.Guardian => "guardian",
_ => s.ToString().ToLowerInvariant(),
};
/// <summary>True for the sections drawn as Mini Remote tabs (all but the Guardian panel).</summary>
public static bool IsTab(IltSection s) => s != IltSection.Guardian;
/// <summary>Parses a "/ra hub open" section name (a few aliases accepted).</summary>
public static bool TryParse(string text, out IltSection section)
{
switch ((text ?? string.Empty).Trim().ToLowerInvariant())
{
case "character": case "char": case "rates": section = IltSection.Character; return true;
case "quests": case "quest": section = IltSection.Quests; return true;
case "pets": case "pet": section = IltSection.Pet; return true;
case "banking": case "bank": section = IltSection.Banking; return true;
case "gear": section = IltSection.Gear; return true;
case "games": case "game": section = IltSection.Games; return true;
case "charms": case "charm": section = IltSection.Charms; return true;
case "guardian": case "temple": case "riddle": section = IltSection.Guardian; return true;
default: section = IltSection.Character; return false;
}
}
/// <summary>"show" / "hide" / "toggle" (anything else toggles) applied to the current state.</summary>
public static bool Resolve(string mode, bool current) => (mode ?? string.Empty).ToLowerInvariant() switch
{
"show" or "on" or "open" => true,
"hide" or "off" or "close" => false,
_ => !current,
};
}

View file

@ -0,0 +1,409 @@
// IltServerOptions.cs — Per-feature enable bits for the ILT Hub, read from the server.
//
// UB gated every Leaftide tool on a single test (WorldName == "InfiniteLeaftide" or a
// Force checkbox). That lies on shards where the operator turned Powerball, /myquests or
// a charm off. This module instead keeps one tri-state bit per feature:
// * World identity: ServerFeatureGate (Settings > Misc server list, or its manual
// override / the Hub's ForceLeaftideFeatures) decides whether we even ASK — it never
// switches a feature on by itself.
// * Preferred source: a structured "/ilt features" dump (ILTFEATURE key=0|1 lines) once
// ACECustom ships it. Today the server prints "Coming Soon", so:
// * Fallback: a one-shot login probe of read-only commands (/bank, /aug, /qb, /pets,
// /shinies, /xp, /pb, /blackjack, /fblackjack, /clap with no args). Replies are eaten.
// /enl is NEVER probed — it opens the enlightenment confirmation dialog.
// * Passive: explicit server refusals seen in chat at any time flip a bit to Off
// ("Powerball lottery is not currently active", "myquests is not currently enabled", ...).
// Unknown bits are treated as OFF by anything that spends currency or runs automation.
using System;
using System.Collections.Generic;
using System.Linq;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthAi.IltHub;
/// <summary>Feature keys used by the gate table.</summary>
internal static class IltFeature
{
public const string Bank = "bank";
public const string Aug = "aug";
public const string Enl = "enl";
public const string Qb = "qb";
public const string Pets = "pets";
public const string Shinies = "shinies";
public const string Xp = "xp";
public const string Blackjack = "blackjack";
public const string FBlackjack = "fblackjack";
public const string Powerball = "powerball";
public const string Quests = "quests";
public const string Clap = "clap";
public const string PetRefill = "pet_refill";
public const string UniversalMastery = "universal_mastery";
public const string RequireComps = "require_spell_comps";
public const string PetBond = "pet_bond";
public const string PetPotency = "pet_potency";
/// <summary>Key for a per-charm "enabled" bit, e.g. Charm("Guardian Hand") → "charm:guardianhand".</summary>
public static string Charm(string charmName)
{
var chars = (charmName ?? string.Empty).Where(char.IsLetterOrDigit).Select(char.ToLowerInvariant).ToArray();
return "charm:" + new string(chars);
}
}
/// <summary>Tri-state feature value.</summary>
internal enum IltTri { Unknown = -1, Off = 0, On = 1 }
internal sealed class IltServerOptions
{
private readonly RynthCoreHost _host;
private readonly IltChatCapture _capture;
private readonly IltHubState _state;
private readonly Action<string> _chat;
private readonly Func<LegacyUiSettings?> _settings;
/// <summary>Feeds probe replies to features that can reuse them (e.g. /bank → Banking balances).</summary>
public Action<string, IltChatResult>? ProbeReplyTap;
private bool _refreshInFlight;
private int _probesOutstanding;
private long _loginAt;
private bool _loginRefreshDone;
/// <summary>Wait this long after login before the one-shot refresh so chat/world are settled.</summary>
private const long LoginRefreshDelayMs = 6000;
/// <summary>
/// Upper bound on waiting for the world name. The engine hook / launch-context file can report
/// it well after the 6 s delay (late inject, Decal coexistence); deciding "not ILT" on an empty
/// name would leave every feature bit Unknown and the Hub hidden for the whole session.
/// </summary>
private const long WorldNameWaitMs = 60000;
public IltServerOptions(RynthCoreHost host, IltChatCapture capture, IltHubState state, Action<string> chat,
Func<LegacyUiSettings?>? settings = null)
{
_host = host;
_capture = capture;
_state = state;
_chat = chat;
_settings = settings ?? (() => null);
}
// ── Identity ────────────────────────────────────────────────────────────
/// <summary>World name as reported by the engine login hook (empty if unknown).</summary>
public string WorldName
{
get
{
if (_host.HasGetWorldName && _host.TryGetWorldName(out string n) && !string.IsNullOrWhiteSpace(n))
return n.Trim();
return _state.ServerOptions.WorldName ?? string.Empty;
}
}
/// <summary>
/// True when the world is (or is declared to be) an ACECustom/ILT shard: its name is in the
/// Settings > Misc server list, or an override is on (ServerFeatureGate).
/// </summary>
public bool IsIltLikeWorld
{
get
{
if (_state.ForceLeaftideFeatures) return true;
LegacyUiSettings? s;
try { s = _settings(); } catch { s = null; }
return ServerFeatureGate.IsEnabled(WorldName, s);
}
}
/// <summary>True while a refresh (dump or probe) is running.</summary>
public bool IsRefreshing => _refreshInFlight;
public string Source => _state.ServerOptions.Source;
public DateTime LastRefreshUtc => _state.ServerOptions.LastRefreshUtc;
// ── Bit access ──────────────────────────────────────────────────────────
public IltTri Get(string key)
=> _state.ServerOptions.Bits.TryGetValue(key, out int v) ? (IltTri)Math.Clamp(v, -1, 1) : IltTri.Unknown;
/// <summary>True only when the server positively reported the feature as available.</summary>
public bool IsOn(string key) => Get(key) == IltTri.On;
/// <summary>True when the server positively reported the feature as unavailable.</summary>
public bool IsOff(string key) => Get(key) == IltTri.Off;
public void Set(string key, IltTri value)
{
// Every feature gate reads these bits, so each transition is traced (IltOptions).
IltTri old = Get(key);
_state.ServerOptions.Bits[key] = (int)value;
if (old != value) RynthLog.Trace(LogCat.IltOptions, $"feature '{key}': {old} -> {value}");
}
/// <summary>At least one feature bit is On (Hub window shows only then, unless Force is on).</summary>
public bool AnyFeatureOn => _state.ServerOptions.Bits.Values.Any(v => v == 1);
/// <summary>All known bits for the status display.</summary>
public IReadOnlyList<KeyValuePair<string, int>> SnapshotBits()
=> _state.ServerOptions.Bits.OrderBy(k => k.Key, StringComparer.OrdinalIgnoreCase).ToList();
// ── Lifecycle ───────────────────────────────────────────────────────────
/// <summary>Called at login: schedules the one-shot refresh (never a recurring timer).</summary>
public void OnLoginComplete()
{
_loginAt = Environment.TickCount64;
_loginRefreshDone = false;
}
/// <summary>
/// Pump-thread tick: fires the delayed login refresh once. While the world name is still
/// unknown it keeps checking (a cheap string compare per tick) until the name arrives or
/// WorldNameWaitMs expires; only a known non-ILT world, or the timeout, ends the wait.
/// </summary>
public void Tick()
{
if (_loginRefreshDone || _loginAt == 0) return;
long sinceLogin = Environment.TickCount64 - _loginAt;
if (sinceLogin < LoginRefreshDelayMs) return;
if (IsIltLikeWorld)
{
_loginRefreshDone = true;
RynthLog.Event(LogEvents.IltWorldCheck,
$"world check: '{WorldName}' is ILT-like (force={_state.ForceLeaftideFeatures}) - refreshing server options");
Refresh(manual: false);
return;
}
// World not reported yet: try again next tick rather than concluding "not ILT".
if (string.IsNullOrEmpty(WorldName) && sinceLogin < WorldNameWaitMs)
return;
_loginRefreshDone = true;
RynthLog.Event(LogEvents.IltWorldCheck,
$"world check: '{WorldName}' is not ILT-like - login refresh skipped (waited {sinceLogin / 1000}s)");
}
/// <summary>
/// Runs the dump-then-probe refresh. Manual refreshes report progress in chat; the
/// login refresh is silent.
/// </summary>
public void Refresh(bool manual)
{
if (_refreshInFlight)
{
if (manual) _chat("[Mini Remote] Server options refresh already running.");
return;
}
if (!IsIltLikeWorld)
{
if (manual) _chat("[Mini Remote] This world is not in the Server Features list (Settings > Misc: add it, or tick the override).");
return;
}
_refreshInFlight = true;
_state.ServerOptions.WorldName = WorldName;
RynthLog.Event(LogEvents.IltOptionsRefreshStart, $"refresh start (manual={manual}, world='{WorldName}')");
if (manual) _chat("[Mini Remote] Refreshing server options...");
// Step 1: structured dump. Lines start with "=== ILT Custom Features ===".
_capture.Enqueue(new IltChatRequest
{
Command = "/ilt features",
IsResponseLine = t => t.StartsWith("ILTFEATURE", StringComparison.OrdinalIgnoreCase)
|| t.Contains("ILT Custom Features", StringComparison.OrdinalIgnoreCase)
|| t.Equals("Coming Soon", StringComparison.OrdinalIgnoreCase),
IdleEndMs = 1200,
FirstLineTimeoutMs = 8000,
Eat = true,
OnComplete = r => OnFeatureDump(r, manual),
});
}
private void OnFeatureDump(IltChatResult r, bool manual)
{
var fromDump = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
foreach (string line in r.Lines)
{
if (!line.StartsWith("ILTFEATURE", StringComparison.OrdinalIgnoreCase)) continue;
foreach (var kv in ParseFeatureLine(line))
{
Set(kv.Key, kv.Value);
fromDump.Add(kv.Key);
}
}
_state.ServerOptions.Source = fromDump.Count > 0 ? "ilt-features" : "probe";
RynthLog.Trace(LogCat.IltOptions, $"feature dump: {fromDump.Count} key(s) (timedOut={r.TimedOut}, unknown={r.UnknownCommand}) → source={_state.ServerOptions.Source}");
RunProbes(fromDump, manual);
}
/// <summary>
/// Parses "ILTFEATURE bank=1 powerball=0 charms=infinitecasting:1,guardianhand:0".
/// ServerConfig-style names ("powerball_enabled") are mapped onto Hub keys.
/// </summary>
internal static IEnumerable<KeyValuePair<string, IltTri>> ParseFeatureLine(string line)
{
string body = line.Substring("ILTFEATURE".Length).Trim();
foreach (string token in body.Split(' ', StringSplitOptions.RemoveEmptyEntries))
{
int eq = token.IndexOf('=');
if (eq <= 0) continue;
string key = token.Substring(0, eq).Trim();
string val = token.Substring(eq + 1).Trim();
if (key.Equals("charms", StringComparison.OrdinalIgnoreCase))
{
foreach (string pair in val.Split(',', StringSplitOptions.RemoveEmptyEntries))
{
int c = pair.IndexOf(':');
if (c <= 0) continue;
yield return new(IltFeature.Charm(pair.Substring(0, c)), ParseTri(pair.Substring(c + 1)));
}
continue;
}
yield return new(MapServerKey(key), ParseTri(val));
}
}
private static IltTri ParseTri(string v)
{
v = v.Trim().ToLowerInvariant();
return v is "1" or "on" or "true" or "yes" ? IltTri.On
: v is "0" or "off" or "false" or "no" ? IltTri.Off
: IltTri.Unknown;
}
private static string MapServerKey(string key)
{
string k = key.Trim().ToLowerInvariant();
return k switch
{
"powerball_enabled" => IltFeature.Powerball,
"quest_info_enabled" => IltFeature.Quests,
"pet_device_pyreal_auto_refill_enabled" => IltFeature.PetRefill,
"pet_charm_universal_summoning_mastery_enabled" => IltFeature.UniversalMastery,
"pet_bond_enabled" => IltFeature.PetBond,
"pet_potency_enabled" => IltFeature.PetPotency,
_ => k.EndsWith("_enabled", StringComparison.Ordinal) ? k.Substring(0, k.Length - "_enabled".Length) : k,
};
}
// ── Probe ───────────────────────────────────────────────────────────────
/// <summary>One read-only probe: command, reply recogniser, feature key.</summary>
private readonly record struct Probe(string Key, string Command, Func<string, bool> IsReply);
private static readonly Probe[] Probes =
{
new(IltFeature.Bank, "/bank", t => t.StartsWith("[BANK]", StringComparison.OrdinalIgnoreCase)
|| t.Contains("not permitted to use bank", StringComparison.OrdinalIgnoreCase)),
new(IltFeature.Aug, "/aug", t => t.StartsWith("---") || t.Contains("Augmentation Levels", StringComparison.OrdinalIgnoreCase)
|| IltParse.AugLine.IsMatch(t)),
new(IltFeature.Qb, "/qb", t => t.StartsWith("Your current quest bonus count", StringComparison.OrdinalIgnoreCase)
|| t.StartsWith("[QB]", StringComparison.OrdinalIgnoreCase)),
new(IltFeature.Pets, "/pets", t => t.Contains("Your Pet Log", StringComparison.OrdinalIgnoreCase)
|| IltParse.RosterLine.IsMatch(t) || t.Contains("Professor Ruggan", StringComparison.OrdinalIgnoreCase)),
new(IltFeature.Shinies, "/shinies", t => t.Contains("Your Shiny Log", StringComparison.OrdinalIgnoreCase)
|| IltParse.RosterLine.IsMatch(t) || t.Contains("Shiny creatures", StringComparison.OrdinalIgnoreCase)),
new(IltFeature.Xp, "/xp", t => t.StartsWith("[XP]", StringComparison.OrdinalIgnoreCase)),
new(IltFeature.Powerball, "/pb", t => t.StartsWith("[Powerball]", StringComparison.OrdinalIgnoreCase)),
new(IltFeature.Blackjack, "/blackjack", IsParamErrorOr("blackjack", "bet amount")),
new(IltFeature.FBlackjack,"/fblackjack", IsParamErrorOr("blackjack", "bet amount")),
new(IltFeature.Clap, "/clap", IsParamErrorOr("clap", "AutoCraftingEnabled")),
};
/// <summary>Recognises ACE's wrong-parameter-count reply (command exists) or a keyword reply.</summary>
private static Func<string, bool> IsParamErrorOr(string keyword, string keyword2) => t =>
t.StartsWith("Invalid parameter count", StringComparison.OrdinalIgnoreCase)
|| t.StartsWith("Usage:", StringComparison.OrdinalIgnoreCase)
|| t.StartsWith("@" + keyword, StringComparison.OrdinalIgnoreCase)
|| t.Contains(keyword2, StringComparison.OrdinalIgnoreCase)
|| (t.Contains(keyword, StringComparison.OrdinalIgnoreCase) && !t.StartsWith("<Tell", StringComparison.OrdinalIgnoreCase));
private void RunProbes(HashSet<string> alreadyKnown, bool manual)
{
var todo = Probes.Where(p => !alreadyKnown.Contains(p.Key)).ToList();
// /enl is never probed (it pops the enlightenment confirmation). On an ILT-like
// world the command is part of ACECustom, so it is assumed present unless the
// dump said otherwise.
if (!alreadyKnown.Contains(IltFeature.Enl))
Set(IltFeature.Enl, IltTri.On);
_probesOutstanding = todo.Count;
if (_probesOutstanding == 0) { CompleteRefresh(manual); return; }
foreach (var p in todo)
{
var probe = p;
_capture.Enqueue(new IltChatRequest
{
Command = probe.Command,
IsResponseLine = probe.IsReply,
IdleEndMs = 1500,
FirstLineTimeoutMs = 8000,
Eat = true,
OnComplete = r =>
{
// Unknown command → Off. Any recognised reply → On. Silence → leave Unknown.
if (r.UnknownCommand) Set(probe.Key, IltTri.Off);
else if (r.Lines.Count > 0) Set(probe.Key, IltTri.On);
RynthLog.Trace(LogCat.IltOptions, $"probe {probe.Command}: lines={r.Lines.Count} unknown={r.UnknownCommand} timedOut={r.TimedOut}");
try { ProbeReplyTap?.Invoke(probe.Key, r); }
catch (Exception ex) { RynthLog.Exception(LogCat.IltOptions, ex, $"probe tap {probe.Key}"); }
if (--_probesOutstanding <= 0) CompleteRefresh(manual);
},
});
}
}
private void CompleteRefresh(bool manual)
{
_refreshInFlight = false;
_state.ServerOptions.LastRefreshUtc = DateTime.UtcNow;
int on = _state.ServerOptions.Bits.Values.Count(v => v == 1);
int off = _state.ServerOptions.Bits.Values.Count(v => v == 0);
// Building the per-bit list is skipped unless the event is actually going to be recorded.
if (RynthLog.IsEventEnabled(LogEvents.IltOptionsRefreshed))
RynthLog.Event(LogEvents.IltOptionsRefreshed, $"options refreshed via {Source} (manual={manual}): {on} on, {off} off - " +
string.Join(" ", _state.ServerOptions.Bits.Select(b => $"{b.Key}={b.Value}")));
if (manual)
_chat($"[Mini Remote] Server options refreshed via {Source}: {on} on, {off} off.");
}
// ── Passive refusals ────────────────────────────────────────────────────
/// <summary>
/// Watches every chat line for explicit server refusals and flips the matching bit Off.
/// Cheap substring checks; runs on the pump thread.
/// </summary>
public void OnChatLine(string text)
{
if (text.Contains("Powerball lottery is not currently active", StringComparison.OrdinalIgnoreCase))
Set(IltFeature.Powerball, IltTri.Off);
else if (text.Contains("\"myquests\" is not currently enabled", StringComparison.OrdinalIgnoreCase))
Set(IltFeature.Quests, IltTri.Off);
else if (text.Contains("\"qb\" is not currently enabled", StringComparison.OrdinalIgnoreCase))
Set(IltFeature.Qb, IltTri.Off);
else if (text.Contains("must have received the AutoCraftingEnabled quest stamp", StringComparison.OrdinalIgnoreCase))
Set(IltFeature.Clap, IltTri.Off);
else if (text.Contains("Universal Summoning Mastery is not enabled on this server", StringComparison.OrdinalIgnoreCase))
Set(IltFeature.UniversalMastery, IltTri.Off);
else if (text.Contains("Auto-Rebuff Charm is currently disabled globally", StringComparison.OrdinalIgnoreCase))
Set(IltFeature.Charm("Auto-Rebuff"), IltTri.Off);
else if (text.Contains("not permitted to use bank commands", StringComparison.OrdinalIgnoreCase))
Set(IltFeature.Bank, IltTri.Off);
}
/// <summary>Records what the login /myquests refresh learned (called by the Hub after the Meta tracker finishes).</summary>
public void NoteQuestTrackerOutcome(bool disabled, int recordCount)
{
if (disabled) Set(IltFeature.Quests, IltTri.Off);
else if (recordCount > 0) Set(IltFeature.Quests, IltTri.On);
}
}

View file

@ -0,0 +1,267 @@
// IltSessionRates.cs — Session earnings / per-hour rates for the ILT Hub Character tab.
//
// Sources (all passive — nothing is sent to the server except the optional bank refresh
// the Banking tab already does):
// XP, luminance (total, last 5 min, allegiance pass-up) and kills: the Mini Remote's
// SessionStatsTracker — RynthTracker's SessionStats code (Plugins\Shared), so this
// table, the Mini Remote and the Tracker panel count them the same way (2026-10-11).
// Coins positive bank Enlightened Coins deltas + carried coin (WCID 300004) gains.
// Pyreals positive bank pyreal deltas + carried pyreal (WCID 273) gains; MMD = 250k.
// Items gains of each item in the item→coin conversion table (carried count),
// converted to potential coins with ItemsPerConversion / CoinsPerConversion.
// A deposit or withdrawal only moves money between pack and bank: while Banking reports one
// (MovingMoney) the coin and pyreal baselines follow along without counting a gain.
using System;
using System.Collections.Generic;
using System.Linq;
using ImGuiNET;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthAi.IltHub;
internal sealed class IltSessionRates : IIltFeature
{
private const long PyrealsPerMmd = 250_000;
private const long SampleIntervalMs = 5000;
private const long RowsIntervalMs = 1000;
private const string PassUpLabel = " pass-up";
private readonly IltHubContext _ctx;
private readonly SessionStatsTracker? _stats;
private DateTime _start = DateTime.UtcNow;
private long _coins;
private long _pyreals;
// Carried-item baselines (last seen counts) for gain tracking.
private long _lastInvCoins = -1;
private long _lastInvPyreals = -1;
private readonly Dictionary<string, long> _lastItemCounts = new(StringComparer.OrdinalIgnoreCase);
private readonly Dictionary<string, long> _itemGains = new(StringComparer.OrdinalIgnoreCase);
private long _lastSampleAt;
private long _lastRowsAt;
// Render snapshot.
private volatile RateRow[] _rows = Array.Empty<RateRow>();
private sealed record RateRow(string Label, string Total, string PerHour);
/// <summary>Coin and pyreal per-hour figures for the Mini Remote HUD (rebuilt every sample).</summary>
public sealed record RateSummary(double CoinsPerHour, double PyrealsPerHour);
private static readonly RateSummary EmptySummary = new(0, 0);
private volatile RateSummary _summary = EmptySummary;
/// <summary>Latest coin / pyreal summary (safe from the render thread).</summary>
public RateSummary Summary => _summary;
/// <summary>When the coin / pyreal session (or the last Reset) started.</summary>
public DateTime SessionStartUtc => _start;
public IltSessionRates(IltHubContext ctx, SessionStatsTracker? stats = null)
{
_ctx = ctx;
_stats = stats;
}
/// <summary>True while money moves between pack and bank (set by the controller from Banking). Pump thread.</summary>
public Func<bool>? MovingMoney { get; set; }
private bool Moving => MovingMoney?.Invoke() ?? false;
/// <summary>Banking hook: bank balance changed (pump thread).</summary>
public void OnBankBalanceChanged(string key, long oldValue, long newValue)
{
RynthLog.Trace(LogCat.IltRates, $"balance {key}: {oldValue} -> {newValue}");
// The first read after login only establishes the baseline (old value is the stale cache).
if (_lastSampleAt == 0) return;
if (Moving) return; // a deposit, not income
long delta = newValue - oldValue;
if (delta <= 0) return; // spending / sending isn't income
if (key == "EnlightenedCoins") _coins += delta;
else if (key == "Pyreals") _pyreals += delta;
}
/// <summary>Coins, pyreals and item gains start over (login, or with <see cref="ResetAll"/>).</summary>
public void Reset()
{
RynthLog.Trace(LogCat.IltRates, $"Reset()");
_start = DateTime.UtcNow;
_coins = _pyreals = 0;
_lastInvCoins = _lastInvPyreals = -1;
_lastItemCounts.Clear();
_itemGains.Clear();
_lastSampleAt = 0;
_lastRowsAt = 0;
_summary = EmptySummary;
}
/// <summary>The player's reset (this tab, the Mini Remote): coins here and the shared session stats together. Pump thread.</summary>
public void ResetAll()
{
Reset();
_stats?.RequestReset();
}
// ── IIltFeature ─────────────────────────────────────────────────────────
public void Tick(long nowMs)
{
// The shared stats move every 0.5 s; their rows refresh each second, coins every 5 s.
if (nowMs - _lastSampleAt < SampleIntervalMs)
{
if (nowMs - _lastRowsAt >= RowsIntervalMs) { _lastRowsAt = nowMs; BuildRows(); }
return;
}
_lastSampleAt = nowMs;
_lastRowsAt = nowMs;
var inv = _ctx.Inventory;
long coinGain = Gain(ref _lastInvCoins, inv.CountByWcid(IltInventory.WcidEnlightenedCoin));
long pyrealGain = Gain(ref _lastInvPyreals, inv.CountByWcid(IltInventory.WcidPyreal));
// A withdrawal: the baselines moved, nothing earned.
if (!Moving)
{
_coins += coinGain;
_pyreals += pyrealGain;
}
// ToArray: the render thread edits this table.
foreach (var conv in _ctx.State.Character.ItemConversions.ToArray())
{
if (string.IsNullOrWhiteSpace(conv.ItemName)) continue;
long count = inv.CountByName(conv.ItemName);
long last = _lastItemCounts.TryGetValue(conv.ItemName, out long l) ? l : -1;
long gain = Gain(ref last, count);
_lastItemCounts[conv.ItemName] = last;
if (gain > 0) _itemGains[conv.ItemName] = (_itemGains.TryGetValue(conv.ItemName, out long g) ? g : 0) + gain;
}
BuildRows();
}
/// <summary>Positive change since the last sample; the first sample only sets the baseline.</summary>
private static long Gain(ref long last, long current)
{
if (last < 0) { last = current; return 0; }
long d = current - last;
last = current;
return d > 0 ? d : 0;
}
// Luminance chat goes to the shared session stats (RynthAiPlugin.OnChatWindowText).
public bool OnChat(string text) => false;
public void OnLogout() => Reset();
// ── Rows ────────────────────────────────────────────────────────────────
private void BuildRows()
{
double hours = Math.Max((DateTime.UtcNow - _start).TotalHours, 1.0 / 3600);
_summary = new RateSummary(_coins / hours, _pyreals / hours);
var s = _stats?.View ?? SessionStatsView.Empty;
var rows = new List<RateRow>
{
new("XP", IltParse.Compact(s.Xp), IltParse.Compact(s.XpPerHour)),
new("Luminance", IltParse.Compact(s.Lum), IltParse.Compact(s.LumPerHour)),
// Per hour at the last five minutes' pace.
new(" last 5 min", IltParse.Compact(s.LumLast5Min), IltParse.Compact(s.LumLast5Min * 12.0)),
};
if (s.PassUpTracked)
rows.Add(new RateRow(PassUpLabel, IltParse.Compact(s.LumPassUp), IltParse.Compact(s.PassUpPerHour)));
rows.Add(new RateRow("Kills", s.Kills.ToString(), s.KillsPerHour.ToString("0")));
rows.Add(new RateRow("Enlightened Coins", IltParse.Compact(_coins), IltParse.Compact(_coins / hours)));
rows.Add(new RateRow("Pyreals", IltParse.Compact(_pyreals), IltParse.Compact(_pyreals / hours)));
rows.Add(new RateRow(" as MMD", (_pyreals / (double)PyrealsPerMmd).ToString("0.0"), (_pyreals / (double)PyrealsPerMmd / hours).ToString("0.0")));
double potentialCoins = 0;
foreach (var conv in _ctx.State.Character.ItemConversions.ToArray())
{
if (!_itemGains.TryGetValue(conv.ItemName, out long gained) || gained == 0) continue;
double coins = conv.ItemsPerConversion > 0 ? gained / (double)conv.ItemsPerConversion * conv.CoinsPerConversion : 0;
potentialCoins += coins;
rows.Add(new RateRow(" " + conv.ItemName, IltParse.N0(gained), IltParse.Compact(gained / hours)));
}
if (potentialCoins > 0)
rows.Add(new RateRow("Potential coins (items)", potentialCoins.ToString("0"), (potentialCoins / hours).ToString("0.0")));
_rows = rows.ToArray();
}
/// <summary>What the pass-up figure is (shared with the Mini Remote's Stats).</summary>
public const string PassUpTooltip =
"Luminance that reached your bank without a \"You've banked\" line: your vassals' pass-up.\n"
+ "Fellowship and Zone Share splits arrive the same silent way and are included.";
// ── UI (render thread) ──────────────────────────────────────────────────
public void Render()
{
// The session clock is the shared stats' (it and the coins reset together).
var start = _stats?.View is { } v && v.SessionSeconds > 0 ? v.SessionStartUtc : _start;
ImGui.TextDisabled($"Session {IltParse.Duration(DateTime.UtcNow - start)}");
ImGui.SameLine();
if (ImGui.SmallButton("Reset##rates")) _ctx.Post(ResetAll);
if (ImGui.BeginTable("##iltrates", 3, ImGuiTableFlags.RowBg | ImGuiTableFlags.BordersInnerV))
{
ImGui.TableSetupColumn("Metric");
ImGui.TableSetupColumn("Session");
ImGui.TableSetupColumn("Per hour");
ImGui.TableHeadersRow();
foreach (var r in _rows)
{
ImGui.TableNextRow();
ImGui.TableNextColumn(); ImGui.TextUnformatted(r.Label);
if (ReferenceEquals(r.Label, PassUpLabel) && ImGui.IsItemHovered()) ImGui.SetTooltip(PassUpTooltip);
ImGui.TableNextColumn(); ImGui.TextUnformatted(r.Total);
ImGui.TableNextColumn(); ImGui.TextColored(LegacyDashboardRenderer.ColTeal, r.PerHour);
}
ImGui.EndTable();
}
if (ImGui.TreeNode("Item -> coin conversions"))
{
RenderConversionEditor();
ImGui.TreePop();
}
}
private string _newItemName = string.Empty;
private void RenderConversionEditor()
{
var list = _ctx.State.Character.ItemConversions;
int remove = -1;
for (int i = 0; i < list.Count; i++)
{
var c = list[i];
ImGui.PushID(i);
ImGui.TextUnformatted(c.ItemName);
ImGui.SameLine(220);
int items = c.ItemsPerConversion, coins = c.CoinsPerConversion;
ImGui.SetNextItemWidth(70);
if (ImGui.InputInt("items", ref items, 0)) c.ItemsPerConversion = Math.Max(1, items);
ImGui.SameLine();
ImGui.SetNextItemWidth(70);
if (ImGui.InputInt("coins", ref coins, 0)) c.CoinsPerConversion = Math.Max(0, coins);
ImGui.SameLine();
if (ImGui.SmallButton("x")) remove = i;
ImGui.PopID();
}
if (remove >= 0)
{
var victim = list[remove];
_ctx.Post(() => list.Remove(victim));
}
ImGui.SetNextItemWidth(200);
ImGui.InputTextWithHint("##newconv", "exact item name", ref _newItemName, 96u);
ImGui.SameLine();
if (ImGui.SmallButton("Add") && _newItemName.Trim().Length > 0
&& !list.Any(c => c.ItemName.Equals(_newItemName.Trim(), StringComparison.OrdinalIgnoreCase)))
{
var added = new IltItemConversion { ItemName = _newItemName.Trim(), ItemsPerConversion = 100, CoinsPerConversion = 0 };
_ctx.Post(() => list.Add(added));
_newItemName = string.Empty;
}
}
}

View file

@ -0,0 +1,114 @@
// IltSigilChain.cs - The Enlightenment Sigil craft chain for /enl 301-325 (ACECustom tier 5:
// T - 5 sigils and T x 2B luminance per target level T). Every craft is one plus one makes one:
// Enlightened Coin + Ancient Yalani Trinket = Ascension Coin
// Life Splitter + Plant = Lifebloom Resin
// Lifebloom Resin + Necrolytic Extract = Lifeblood Elixir
// Lifeblood Elixir + Ascension Coin = Enlightenment Sigil
// Pure math (no host access) so the planner and the host tests share it. Mirrors UB-IT's
// EnlightenmentSigilChainPolicy.
using System;
namespace RynthCore.Plugin.RynthAi.IltHub;
/// <summary>Stack counts of every item in the sigil chain.</summary>
internal sealed class IltSigilStock
{
public long Sigils, AscensionCoins, LifebloodElixirs, LifebloomResins;
public long EnlightenedCoins, YalaniTrinkets, NecrolyticExtracts, LifeSplitters, Plants;
public IltSigilStock Clone() => (IltSigilStock)MemberwiseClone();
}
/// <summary>
/// What a sigil demand still needs after using stock from the top of the chain down. "ToCraft" are
/// crafts left to do (intermediates); "Short" are raw materials left to get.
/// </summary>
internal sealed class IltSigilShortfall
{
public long SigilsNeeded, SigilsToCraft, AscensionToCraft, ElixirsToCraft, ResinsToCraft;
/// <summary>E-coins the Ascension Coin crafts use (before stock).</summary>
public long CoinsForCraft;
public long CoinsShort, TrinketsShort, ExtractsShort, SplittersShort, PlantsShort;
/// <summary>Stock (with the whole chain) covers every sigil.</summary>
public bool Covered => CoinsShort == 0 && TrinketsShort == 0 && ExtractsShort == 0 && SplittersShort == 0 && PlantsShort == 0;
}
internal static class IltSigilChain
{
public const int FirstTarget = 301;
public const int LastTarget = 325;
// Item names (ACECustom ships no WCIDs for these yet, so they are counted by name).
public const string AscensionCoin = "Ascension Coin";
public const string YalaniTrinket = "Ancient Yalani Trinket";
public const string LifeSplitter = "Life Splitter";
public const string Plant = "Plant";
public const string LifebloomResin = "Lifebloom Resin";
public const string NecrolyticExtract = "Necrolytic Extract";
public const string LifebloodElixir = "Lifeblood Elixir";
public static bool IsSigilTarget(int t) => t >= FirstTarget && t <= LastTarget;
/// <summary>Sigils for target levels current+1 .. target that fall inside 301-325 (T - 5 each).</summary>
public static long SigilsForRange(int current, int target)
{
long total = 0;
for (int t = Math.Max(current + 1, FirstTarget); t <= Math.Min(target, LastTarget); t++)
total += Math.Max(0, t - 5);
return total;
}
/// <summary>Shortfall for <paramref name="sigilsNeeded"/>: sigils first, then coins / elixirs, then resins, then raws.</summary>
public static IltSigilShortfall Shortfall(long sigilsNeeded, IltSigilStock stock)
{
var s = new IltSigilShortfall { SigilsNeeded = Math.Max(0, sigilsNeeded) };
if (s.SigilsNeeded == 0) return s;
stock ??= new IltSigilStock();
s.SigilsToCraft = Short(s.SigilsNeeded, stock.Sigils);
s.AscensionToCraft = Short(s.SigilsToCraft, stock.AscensionCoins);
s.ElixirsToCraft = Short(s.SigilsToCraft, stock.LifebloodElixirs);
s.CoinsForCraft = s.AscensionToCraft;
s.CoinsShort = Short(s.AscensionToCraft, stock.EnlightenedCoins);
s.TrinketsShort = Short(s.AscensionToCraft, stock.YalaniTrinkets);
s.ResinsToCraft = Short(s.ElixirsToCraft, stock.LifebloomResins);
s.ExtractsShort = Short(s.ElixirsToCraft, stock.NecrolyticExtracts);
s.SplittersShort = Short(s.ResinsToCraft, stock.LifeSplitters);
s.PlantsShort = Short(s.ResinsToCraft, stock.Plants);
return s;
}
/// <summary>Sigils the stock can make: finished sigils plus the scarcer of the two craft paths.</summary>
public static long Fulfillable(IltSigilStock stock)
{
if (stock == null) return 0;
long coins = stock.AscensionCoins + Math.Min(stock.EnlightenedCoins, stock.YalaniTrinkets);
long resins = stock.LifebloomResins + Math.Min(stock.LifeSplitters, stock.Plants);
long elixirs = stock.LifebloodElixirs + Math.Min(resins, stock.NecrolyticExtracts);
return stock.Sigils + Math.Min(coins, elixirs);
}
/// <summary>
/// Splits the e-coin pool between Ascension Coin crafts (served first) and token conversion.
/// <paramref name="coinsNeeded"/> is what is still to get for both.
/// </summary>
public static void EcoinDemand(long coinsHave, long coinsForSigils, long tokensShort, int coinsPerToken,
out long tokensFromCoins, out long tokensStill, out long coinsNeeded)
{
long rate = Math.Max(1, coinsPerToken);
long have = Math.Max(0, coinsHave), sigil = Math.Max(0, coinsForSigils), tok = Math.Max(0, tokensShort);
tokensFromCoins = Math.Min(tok, Math.Max(0, have - sigil) / rate);
tokensStill = tok - tokensFromCoins;
coinsNeeded = Math.Max(0, sigil - have) + tokensStill * rate;
}
/// <summary>True for a chain item name (stack names may be plural; "Plant" must be the whole name).</summary>
public static bool NameIs(string itemName, string chainName)
{
string n = (itemName ?? string.Empty).Trim();
return n.Equals(chainName, StringComparison.OrdinalIgnoreCase)
|| n.Equals(chainName + "s", StringComparison.OrdinalIgnoreCase);
}
private static long Short(long demand, long have) => Math.Max(0, demand - Math.Max(0, have));
}

View file

@ -0,0 +1,205 @@
// IltSplitArrows.cs — Split-arrow imbuer (Gear tab, P2).
//
// ILT missile weapons carry a split-arrow count (int 9031). Each White Quartz salvage
// application adds one split and uses one tink. Per weapon:
// needed = min(target - current, 10 - tinks, 10 - current)
// The imbuer applies full (100-unit) White Quartz bags, lowest workmanship first, with
// UseObjectOn(salvage, weapon). AC then shows its own craft confirmation — the player
// clicks it; the imbuer waits (20 s) for the "successfully applies" / "fails to apply"
// line before the next step. Nothing is ever applied without the Hub confirm first.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using ImGuiNET;
using RynthCore.Loot;
using RynthCore.Plugin.RynthAi.LegacyUi;
namespace RynthCore.Plugin.RynthAi.IltHub;
internal sealed class IltSplitArrows : IIltFeature
{
private const int MaterialWhiteQuartz = 46;
private const uint IntNumItemsInMaterial = 170;
private const uint IntItemWorkmanship = 105;
private const long StepTimeoutMs = 20_000;
private static readonly Regex Applied = new(
@"^(?<character>[\w\s]+) successfully applies the (?<salvage>[\w\s\-]+?)(\sSalvage.*)(\s?\(100\))?\s\(workmanship (?<workmanship>\d+\.\d+)\) to the (?<item>[\w\s\'\-]+)\.$",
RegexOptions.Compiled | RegexOptions.CultureInvariant);
private static readonly Regex Failed = new(
@"^(?<character>[\w\s]+) fails to apply the (?<salvage>[\w\s\-]+?)(\sSalvage.*)(\s?\(100\))?\s\(workmanship (?<workmanship>\d+\.\d+)\) to the (?<item>[\w\s\'\-]+)\.",
RegexOptions.Compiled | RegexOptions.CultureInvariant);
private readonly IltHubContext _ctx;
// Job state (pump thread)
private int _weaponId;
private int _remaining;
private bool _waiting;
private long _stepStartedAt;
private volatile string _status = "idle";
// Render snapshot of eligible weapons
private volatile WeaponRow[] _weapons = Array.Empty<WeaponRow>();
private long _lastScan;
private sealed record WeaponRow(int Id, string Name, int Splits, int Tinks, bool Imbued, int Needed);
public IltSplitArrows(IltHubContext ctx) => _ctx = ctx;
private IltGearState G => _ctx.State.Gear;
public bool Running => _weaponId != 0;
private int Needed(WorldObject w)
{
var inv = _ctx.Inventory;
int cur = inv.Int(w, IltInventory.IntSplitArrowCount);
int tinks = inv.Int(w, IltInventory.IntNumTimesTinkered);
int target = Math.Clamp(G.SplitArrowTarget, 0, 10);
return Math.Max(0, Math.Min(target - cur, Math.Min(10 - tinks, 10 - cur)));
}
/// <summary>Full White Quartz bags, lowest workmanship first.</summary>
private List<WorldObject> QuartzBags()
{
var inv = _ctx.Inventory;
return inv.Items()
.Where(wo => wo.ObjectClass == AcObjectClass.Salvage
&& (inv.Int(wo, IltInventory.IntMaterialType) == MaterialWhiteQuartz || wo.Name.Contains("White Quartz", StringComparison.OrdinalIgnoreCase))
&& inv.Uses(wo) >= 100)
.OrderBy(Workmanship)
.ToList();
}
private double Workmanship(WorldObject bag)
{
int total = _ctx.Inventory.Int(bag, IntItemWorkmanship);
int items = Math.Max(1, _ctx.Inventory.Int(bag, IntNumItemsInMaterial, 1));
return total / (double)items;
}
/// <summary>Starts imbuing one weapon (pump thread, after the UI confirm).</summary>
public void Start(int weaponId)
{
var w = _ctx.Inventory.Cache?[weaponId];
if (w == null) { _status = "weapon not found"; return; }
if (_ctx.Inventory.IsEquipped(w)) { _status = "unequip the weapon first"; return; }
int need = Needed(w);
if (need <= 0) { _status = $"{w.Name} needs no more splits"; return; }
_weaponId = weaponId;
_remaining = need;
_waiting = false;
_status = $"imbuing {w.Name}: {need} application(s)";
}
public void Stop(string why)
{
_weaponId = 0;
_waiting = false;
_status = why;
}
// ── IIltFeature ─────────────────────────────────────────────────────────
public void Tick(long nowMs)
{
if (nowMs - _lastScan >= 3000 && _ctx.WindowOpen)
{
_lastScan = nowMs;
ScanWeapons();
}
if (_weaponId == 0) return;
if (_waiting)
{
if (nowMs - _stepStartedAt > StepTimeoutMs) Stop("no result within 20 s (craft dialog not confirmed?) - stopped");
return;
}
if (_remaining <= 0) { Stop("done"); return; }
if (_ctx.Inventory.IsBusy) return;
var bag = QuartzBags().FirstOrDefault();
if (bag == null) { Stop("out of full White Quartz bags"); return; }
if (_ctx.Inventory.UseOn(bag, unchecked((uint)_weaponId)))
{
_waiting = true;
_stepStartedAt = nowMs;
_status = $"applying {bag.Name} - confirm the craft dialog in AC ({_remaining} left)";
}
}
public bool OnChat(string text)
{
if (!_waiting) return false;
if (Applied.IsMatch(text))
{
_waiting = false;
_remaining--;
_status = $"applied ({_remaining} left)";
}
else if (Failed.IsMatch(text))
{
// A failed tink still consumes a tink slot — recompute from the weapon.
_waiting = false;
var w = _ctx.Inventory.Cache?[_weaponId];
_remaining = w != null ? Math.Min(_remaining, Needed(w)) : 0;
_status = $"application failed ({_remaining} left)";
}
return false;
}
public void OnLogout() => Stop("idle");
private void ScanWeapons()
{
var inv = _ctx.Inventory;
var rows = new List<WeaponRow>();
foreach (var wo in inv.Items())
{
if (wo.ObjectClass != AcObjectClass.MissileWeapon) continue;
bool imbued = inv.Int(wo, IltInventory.IntImbuedEffect) != 0;
if (imbued && G.SplitIgnoreImbued) continue;
rows.Add(new WeaponRow(wo.Id, wo.Name, inv.Int(wo, IltInventory.IntSplitArrowCount),
inv.Int(wo, IltInventory.IntNumTimesTinkered), imbued, Needed(wo)));
}
_weapons = rows.OrderByDescending(r => r.Needed).ThenBy(r => r.Name).ToArray();
_bagCount = QuartzBags().Count;
}
private volatile int _bagCount;
// ── UI (render thread) ──────────────────────────────────────────────────
public void Render()
{
ImGui.TextColored(LegacyDashboardRenderer.ColTeal, "Split arrows (White Quartz)");
int tgt = G.SplitArrowTarget;
ImGui.SetNextItemWidth(120);
if (ImGui.SliderInt("Target splits", ref tgt, 0, 10)) G.SplitArrowTarget = tgt;
ImGui.SameLine();
bool skip = G.SplitIgnoreImbued;
if (ImGui.Checkbox("Skip imbued weapons", ref skip)) G.SplitIgnoreImbued = skip;
ImGui.TextDisabled($"Full White Quartz bags carried: {_bagCount}");
foreach (var w in _weapons)
{
ImGui.PushID(w.Id);
ImGui.TextUnformatted($"{w.Name} splits {w.Splits}, tinks {w.Tinks}{(w.Imbued ? ", imbued" : "")}");
ImGui.SameLine();
ImGui.BeginDisabled(w.Needed <= 0 || Running);
if (ImGui.SmallButton($"Imbue +{w.Needed}"))
{
var row = w;
_ctx.Confirm("Split-arrow imbue",
$"Apply {row.Needed} White Quartz bag(s) to {row.Name}?\n\nEach application uses a tink and can fail.\n"
+ "AC will ask you to confirm every craft.",
() => Start(row.Id), "Start");
}
ImGui.EndDisabled();
ImGui.PopID();
}
if (_weapons.Length == 0) ImGui.TextDisabled("No missile weapons carried.");
if (Running && ImGui.SmallButton("Stop imbuing")) _ctx.Post(() => Stop("stopped by player"));
ImGui.TextDisabled("Status: " + _status);
}
}

View file

@ -0,0 +1,298 @@
// IltTempleAttributes.cs - Temple of Enlightenment attribute turn-in tracker (Guardian window).
//
// One row per Fiun attribute NPC plus the Guardian of Attribute Enlightenment riddle. Each row
// prefers the timed flag from /myquests (solves + exact cooldown). When /myquests lacks the flag
// it falls back to the "/qb list" wait stamp: a stamp appearing between two lists counts one
// turn-in and starts an estimated cooldown (CooldownHoursAssumed). Fallback counts and timers
// persist in IltGuardianState.
//
// Rows come from "infi attribute.csv" (RynthAi folder, then Documents\Asheron's Call - the UB
// location) when present: npc, attribute, stamp [, myQuestsKey]. Built-in rows missing from the
// file are appended. Pump thread computes; the render thread only reads Snapshot.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using RynthCore.Install;
using RynthCore.Plugin.RynthAi.Meta;
namespace RynthCore.Plugin.RynthAi.IltHub;
/// <summary>One tracked turn-in: the NPC, its attribute, the /qb wait flag and the /myquests keys to try.</summary>
internal sealed class IltTempleAttrRow
{
public IltTempleAttrRow(string npc, string attribute, string stamp, string? myQuestsKey = null)
{
Npc = npc.Trim();
Attribute = attribute.Trim();
QbWaitFlag = ExtractQbFlag(stamp);
var keys = new List<string>();
void Add(string? k)
{
if (string.IsNullOrWhiteSpace(k)) return;
string t = k.Trim().ToLowerInvariant();
if (!keys.Contains(t)) keys.Add(t);
}
Add(myQuestsKey);
Add(QbWaitFlag);
if (QbWaitFlag.EndsWith("Wait", StringComparison.OrdinalIgnoreCase) && QbWaitFlag.Length > 4)
Add(QbWaitFlag[..^4]);
MyQuestsKeys = keys.ToArray();
}
public string Npc { get; }
public string Attribute { get; }
/// <summary>/qb flag name (e.g. TempleAttributeStrengthWait).</summary>
public string QbWaitFlag { get; }
/// <summary>Lowercase /myquests keys in lookup order: CSV override, the wait flag, the flag without "Wait".</summary>
public string[] MyQuestsKeys { get; }
/// <summary>"You've stamped X!" → "X"; a bare flag name is returned trimmed.</summary>
private static string ExtractQbFlag(string stamp)
{
string s = (stamp ?? string.Empty).Trim();
const string prefix = "You've stamped ";
if (s.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)) s = s[prefix.Length..];
return s.Trim().TrimEnd('!', ' ', '\t', '\r', '\n');
}
}
/// <summary>What the Guardian window shows for one row.</summary>
internal sealed record IltTempleAttrStatus(string Attribute, string Npc, int Count, string Status, string Eta, bool Ready, bool FromMyQuests);
internal sealed class IltTempleAttributes
{
private const long RebuildIntervalMs = 1000;
private const string CsvName = "infi attribute.csv";
private static readonly IltTempleAttrRow[] DefaultRows =
{
new("Fiun Luunere", "Strength", "TempleAttributeStrengthWait"),
new("Fiun Bayaas", "Coordination", "TempleAttributeCoordinationWait"),
new("Fiun Ruun", "Endurance", "TempleAttributeEnduranceWait"),
new("Fiun Riish", "Quickness", "TempleAttributeQuicknessWait"),
new("Fiun Vasherr", "Focus", "TempleAttributeFocusWait"),
new("Fiun Noress", "Willpower", "TempleAttributeSelfWait"),
new("Fiun Vaelesh", "Health", "TempleAttributeHealthWait"),
new("Fiun Torrun", "Stamina", "TempleAttributeStamWait"),
new("Fiun Saeluun", "Mana", "TempleAttributeManaWait"),
new("Guardian (Attr)", "Riddle", "TempleAttributeRiddleWait"),
};
private readonly IltHubContext _ctx;
private readonly Func<QuestTracker?> _tracker;
private readonly IltQuests _quests;
private readonly IltTempleAttrRow[] _rows;
// Wait-stamp presence per attribute at the previous "/qb list" (session only: a transition
// needs two lists in the same session).
private readonly Dictionary<string, bool> _lastHadWait = new(StringComparer.OrdinalIgnoreCase);
private int _seenQbGeneration;
private long _lastRebuildAt = -RebuildIntervalMs;
private volatile IltTempleAttrStatus[] _snapshot = Array.Empty<IltTempleAttrStatus>();
private DateTime _syncedUtc = DateTime.MinValue;
public IltTempleAttributes(IltHubContext ctx, Func<QuestTracker?> tracker, IltQuests quests)
{
_ctx = ctx;
_tracker = tracker;
_quests = quests;
_rows = LoadRows(out string source);
RynthLog.Write(LogCat.IltHub, $"[IltGuardian] attribute rows: {_rows.Length} from {source}");
}
/// <summary>Rows as last computed (render thread reads this).</summary>
public IltTempleAttrStatus[] Snapshot => _snapshot;
/// <summary>When the quest data behind the rows last changed (MinValue = never this session).</summary>
public DateTime SyncedUtc => _syncedUtc;
private IltGuardianState S => _ctx.State.Guardian;
// ── Rows file ───────────────────────────────────────────────────────────
/// <summary>The CSV in the RynthAi folder, else UB's Documents location; built-in rows otherwise.</summary>
private static IltTempleAttrRow[] LoadRows(out string source)
{
string[] candidates =
{
Path.Combine(RynthInstallPaths.RynthAiDir, CsvName),
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "Asheron's Call", CsvName),
};
foreach (string path in candidates)
{
try
{
if (!File.Exists(path)) continue;
var rows = ParseCsv(File.ReadAllLines(path));
if (rows.Count == 0) continue;
source = path;
return MergeMissingDefaults(rows);
}
catch (Exception ex) { RynthLog.Exception(LogCat.IltHub, ex, $"read {path}"); }
}
source = "built-in table";
return DefaultRows;
}
/// <summary>npc, attribute, stamp [, myQuestsKey]; a header row and blank lines are skipped.</summary>
private static List<IltTempleAttrRow> ParseCsv(string[] lines)
{
var rows = new List<IltTempleAttrRow>();
foreach (string raw in lines)
{
string line = raw.Trim().TrimStart('\uFEFF');
if (line.Length == 0) continue;
if (line.StartsWith("npc", StringComparison.OrdinalIgnoreCase) && line.Contains("attribute", StringComparison.OrdinalIgnoreCase))
continue;
string[] seg = line.Split(',');
if (seg.Length < 3) continue;
string npc = seg[0].Trim(), attr = seg[1].Trim();
string stamp;
string? key = null;
if (seg.Length == 4) { stamp = seg[2].Trim(); key = seg[3].Trim(); }
else stamp = string.Join(",", seg.Skip(2)).Trim(); // a full stamp chat line may contain commas
if (npc.Length == 0 || attr.Length == 0 || stamp.Length == 0) continue;
rows.Add(new IltTempleAttrRow(npc, attr, stamp, key));
}
return rows;
}
private static IltTempleAttrRow[] MergeMissingDefaults(List<IltTempleAttrRow> loaded)
{
var seen = new HashSet<string>(loaded.Select(r => r.QbWaitFlag), StringComparer.OrdinalIgnoreCase);
foreach (var def in DefaultRows)
if (seen.Add(def.QbWaitFlag)) loaded.Add(def);
return loaded.ToArray();
}
// ── Pump thread ─────────────────────────────────────────────────────────
public void Tick(long nowMs)
{
int gen = _quests.QbGeneration;
if (gen != _seenQbGeneration)
{
_seenQbGeneration = gen;
if (gen > 0) ApplyQbTransitions();
_syncedUtc = DateTime.UtcNow;
}
if (nowMs - _lastRebuildAt < RebuildIntervalMs) return;
_lastRebuildAt = nowMs;
Rebuild();
}
/// <summary>Re-asks the server for /myquests and "/qb list" (each limited to once a minute).</summary>
public string Refresh() => $"{_quests.RefreshQuests()} {_quests.RefreshQb()}";
/// <summary>Forgets the counted turn-ins and estimated cooldowns (the /qb fallback only).</summary>
public void ResetCounts()
{
S.TurnInCounts.Clear();
S.CooldownUntilUtc.Clear();
_lastRebuildAt = long.MinValue / 2;
}
public void OnLogout()
{
_lastHadWait.Clear();
_seenQbGeneration = 0;
_syncedUtc = DateTime.MinValue;
}
private bool TryQuest(IltTempleAttrRow row, out QuestRecord rec)
{
rec = null!;
var t = _tracker();
if (t == null) return false;
foreach (string key in row.MyQuestsKeys)
if (t.TryGetFlag(key, out rec)) return true;
return false;
}
/// <summary>A new "/qb list" arrived: count wait stamps that appeared since the previous list.</summary>
private void ApplyQbTransitions()
{
int hours = Math.Max(1, S.CooldownHoursAssumed);
foreach (var row in _rows)
{
string key = row.Attribute;
bool hasWait = _quests.QbHasFlag(row.QbWaitFlag);
if (!TryQuest(row, out _))
{
if (_lastHadWait.TryGetValue(key, out bool had) && !had && hasWait)
{
S.TurnInCounts[key] = (S.TurnInCounts.TryGetValue(key, out int n) ? n : 0) + 1;
S.CooldownUntilUtc[key] = DateTime.UtcNow.AddHours(hours);
RynthLog.Write(LogCat.IltHub, $"[IltGuardian] {key} turn-in counted from /qb (now {S.TurnInCounts[key]})");
}
if (!hasWait) S.CooldownUntilUtc.Remove(key);
}
_lastHadWait[key] = hasWait;
}
}
private void Rebuild()
{
bool qbLoaded = _quests.QbGeneration > 0;
int hours = Math.Max(1, S.CooldownHoursAssumed);
var list = new IltTempleAttrStatus[_rows.Length];
for (int i = 0; i < _rows.Length; i++)
{
var row = _rows[i];
if (TryQuest(row, out var rec))
{
list[i] = FromQuest(row, rec);
continue;
}
string key = row.Attribute;
int count = S.TurnInCounts.TryGetValue(key, out int c) ? c : 0;
if (!qbLoaded)
{
list[i] = new(key, row.Npc, count, "Unknown", "Refresh", false, false);
continue;
}
if (!_quests.QbHasFlag(row.QbWaitFlag))
{
list[i] = new(key, row.Npc, count, "Ready", "-", true, false);
continue;
}
// Wait stamp present: show the estimated cooldown, starting one if none is known.
if (!S.CooldownUntilUtc.TryGetValue(key, out DateTime until))
S.CooldownUntilUtc[key] = until = DateTime.UtcNow.AddHours(hours);
until = AsUtc(until);
TimeSpan left = until - DateTime.UtcNow;
list[i] = left > TimeSpan.Zero
? new(key, row.Npc, count, "Wait stamp", $"~{IltParse.Duration(left)} (est.)", false, false)
: new(key, row.Npc, count, "Wait stamp", "ready? (est.)", false, false);
}
_snapshot = list;
}
/// <summary>A row backed by its /myquests flag: exact solves and cooldown.</summary>
private static IltTempleAttrStatus FromQuest(IltTempleAttrRow row, QuestRecord rec)
{
switch (IltQuests.Classify(rec))
{
case IltQuests.QuestKind.KillTask:
return new(row.Attribute, row.Npc, rec.Solves, "Kill task", $"{rec.Solves}/{rec.MaxSolves}", false, true);
case IltQuests.QuestKind.Once:
return new(row.Attribute, row.Npc, rec.Solves, "Once", rec.Solves >= 1 ? "done" : "-", false, true);
default:
if (rec.IsReady()) return new(row.Attribute, row.Npc, rec.Solves, "Ready", "now", true, true);
TimeSpan left = rec.TimeUntilReady();
string at = DateTime.Now.Add(left).ToString("ddd HH:mm");
return new(row.Attribute, row.Npc, rec.Solves, "Cooldown", $"{IltParse.Duration(left)} ({at})", false, true);
}
}
/// <summary>Stored times may load as Unspecified; they were written as UTC.</summary>
private static DateTime AsUtc(DateTime dt) => dt.Kind switch
{
DateTimeKind.Utc => dt,
DateTimeKind.Local => dt.ToUniversalTime(),
_ => DateTime.SpecifyKind(dt, DateTimeKind.Utc),
};
}

View file

@ -0,0 +1,351 @@
// IltUsdImporter.cs — VirindiTank .usd settings → RynthAi monster / weapon / consumable rules (Gear tab, P2).
//
// .usd is VTank's line-based table dump. Each table is:
// <table name>
// <column count 1..32>
// <column name> x count
// <column type token> x count
// <row count>
// per cell: <tag line s|i|b|d|...> then <value line>
// Tables we read: MyMonsters (monster rules), weapons/wands/shields/combatitems (weapon
// rules), pets (pet essences), items/itemlist/buffeditems/AssistItems (consumables).
// Object ids are resolved against the current inventory (id first, then name). The
// import is previewed first and only applied after a confirm; existing rules with the
// same name / id are replaced, everything else is kept.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using ImGuiNET;
using RynthCore.Loot;
using RynthCore.Plugin.RynthAi.LegacyUi;
namespace RynthCore.Plugin.RynthAi.IltHub;
internal sealed class IltUsdImporter
{
/// <summary>Default VTank profile folder when the Decal registry value is unavailable.</summary>
public const string DefaultVtProfileDir = @"C:\Games\VirindiPlugins\VirindiTank\";
private static readonly string[] Elements = { "Slash", "Pierce", "Bludgeon", "Fire", "Cold", "Lightning", "Acid", "Nether" };
private static readonly HashSet<string> WeaponTables = new(StringComparer.OrdinalIgnoreCase) { "weapons", "wands", "shields", "combatitems" };
private static readonly HashSet<string> ConsumableTables = new(StringComparer.OrdinalIgnoreCase) { "items", "itemlist", "buffeditems", "assistitems" };
/// <summary>One parsed table: column names and rows of raw cell strings.</summary>
private sealed class UsdTable
{
public string Name = string.Empty;
public string[] Columns = Array.Empty<string>();
public List<string[]> Rows = new();
public string Get(string[] row, params string[] names)
{
foreach (string n in names)
{
int i = Array.FindIndex(Columns, c => c.Equals(n, StringComparison.OrdinalIgnoreCase));
if (i >= 0 && i < row.Length) return row[i] ?? string.Empty;
}
return string.Empty;
}
}
/// <summary>Result of a preview: the rules that would be written.</summary>
private sealed class ImportPlan
{
public string Path = string.Empty;
public List<MonsterRule> Monsters = new();
public List<ItemRule> Weapons = new();
public List<ConsumableRule> Consumables = new();
public List<string> Notes = new();
}
private readonly IltHubContext _ctx;
private volatile ImportPlan? _plan;
private volatile string _status = string.Empty;
private string _pathInput = string.Empty;
public IltUsdImporter(IltHubContext ctx)
{
_ctx = ctx;
_pathInput = ctx.State.Gear.LastUsdPath;
}
/// <summary>VTank's profile folder from Decal's registry entry, else the default install path.</summary>
public static string VtProfileDir()
{
try
{
using var key = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(@"Software\Decal\Plugins\{642F1F48-16BE-48BF-B1D4-286652C4533E}");
if (key?.GetValue("ProfilePath") is string p && p.Length > 0 && Directory.Exists(p)) return p;
}
catch { /* registry unavailable: fall back */ }
return DefaultVtProfileDir;
}
// ── Parsing ─────────────────────────────────────────────────────────────
private static List<UsdTable> Parse(string[] lines)
{
var tables = new List<UsdTable>();
int i = 0;
while (i < lines.Length - 1)
{
string name = lines[i].Trim();
if (name.Length == 0 || !int.TryParse(lines[i + 1].Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out int cols)
|| cols < 1 || cols > 32 || name.Any(char.IsWhiteSpace))
{
i++;
continue;
}
int p = i + 2;
if (p + cols * 2 >= lines.Length) { i++; continue; }
var t = new UsdTable { Name = name, Columns = new string[cols] };
for (int c = 0; c < cols; c++) t.Columns[c] = lines[p++].Trim();
p += cols; // type tokens
if (p >= lines.Length || !int.TryParse(lines[p].Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out int rows) || rows < 0 || rows > 100_000)
{
i++;
continue;
}
p++;
bool ok = true;
for (int r = 0; r < rows && ok; r++)
{
var row = new string[cols];
for (int c = 0; c < cols; c++)
{
if (p + 1 >= lines.Length) { ok = false; break; }
// Every cell is a tag line plus a value line; unknown tags are still two lines.
row[c] = lines[p + 1].Trim();
p += 2;
}
if (ok) t.Rows.Add(row);
}
tables.Add(t);
i = p;
}
return tables;
}
private static int ParseId(string s)
{
s = s.Trim();
if (s.StartsWith("0x", StringComparison.OrdinalIgnoreCase)
&& int.TryParse(s.AsSpan(2), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out int hex)) return hex;
if (long.TryParse(s, NumberStyles.Integer, CultureInfo.InvariantCulture, out long l)) return unchecked((int)l);
return 0;
}
private static bool ValidId(int id) => id != 0 && id != -1 && id != -5;
private static bool ParseBool(string s)
=> s.Equals("true", StringComparison.OrdinalIgnoreCase) || s == "1" || s.Equals("yes", StringComparison.OrdinalIgnoreCase);
/// <summary>VTank damage value (name or AC damage-type bitmask) → RynthAi element, or null.</summary>
private static string? MapElement(string v)
{
v = v.Trim();
if (v.Length == 0) return null;
foreach (string e in Elements) if (v.Equals(e, StringComparison.OrdinalIgnoreCase)) return e;
if (v.StartsWith("Bludg", StringComparison.OrdinalIgnoreCase)) return "Bludgeon";
if (v.StartsWith("Pierc", StringComparison.OrdinalIgnoreCase)) return "Pierce";
if (v.StartsWith("Electric", StringComparison.OrdinalIgnoreCase)) return "Lightning";
if (v.StartsWith("Void", StringComparison.OrdinalIgnoreCase)) return "Nether";
if (!int.TryParse(v, NumberStyles.Integer, CultureInfo.InvariantCulture, out int dt) || dt <= 0) return null;
return BitsToElement(dt);
}
private static string? BitsToElement(int dt)
{
if ((dt & 1024) != 0) return "Nether";
if ((dt & 16) != 0) return "Fire";
if ((dt & 8) != 0) return "Cold";
if ((dt & 64) != 0) return "Lightning";
if ((dt & 32) != 0) return "Acid";
if ((dt & 4) != 0) return "Bludgeon";
if ((dt & 2) != 0) return "Pierce";
if ((dt & 1) != 0) return "Slash";
return null;
}
/// <summary>Resolves a USD object (id, name) to a carried item.</summary>
private WorldObject? Resolve(int id, string name)
{
var cache = _ctx.Inventory.Cache;
if (cache == null) return null;
if (ValidId(id))
{
var byId = cache[id];
if (byId != null) return byId;
}
if (string.IsNullOrWhiteSpace(name)) return null;
return _ctx.Inventory.Items().FirstOrDefault(w => w.Name.Equals(name.Trim(), StringComparison.OrdinalIgnoreCase));
}
private static string ConsumableType(string name)
{
string n = name.ToLowerInvariant();
if (n.Contains("essence")) return "Pet";
if (n.Contains("kit")) return "HealthKit";
if (n.Contains("mana stone") || n.Contains("mana charge")) return "ManaStone";
if (n.Contains("stamina")) return "Stamina";
if (n.Contains("lockpick")) return "Lockpick";
return "General";
}
// ── Preview / apply (pump thread) ───────────────────────────────────────
public void Preview(string path)
{
path = (path ?? string.Empty).Trim().Trim('"');
if (path.Length > 0 && !Path.IsPathRooted(path)) path = Path.Combine(VtProfileDir(), path);
if (!File.Exists(path)) { _status = "File not found: " + path; _plan = null; return; }
string[] lines;
try { lines = File.ReadAllLines(path); }
catch (Exception ex) { _status = "Read failed: " + ex.Message; _plan = null; return; }
var plan = new ImportPlan { Path = path };
foreach (var t in Parse(lines))
{
if (t.Name.Equals("MyMonsters", StringComparison.OrdinalIgnoreCase)) PlanMonsters(t, plan);
else if (WeaponTables.Contains(t.Name)) PlanWeapons(t, plan);
else if (t.Name.Equals("pets", StringComparison.OrdinalIgnoreCase)) PlanConsumables(t, plan, forceType: "Pet");
else if (ConsumableTables.Contains(t.Name)) PlanConsumables(t, plan, forceType: null);
}
_ctx.State.Gear.LastUsdPath = path;
_plan = plan;
_status = $"Preview: {plan.Monsters.Count} monsters, {plan.Weapons.Count} weapons, {plan.Consumables.Count} consumables.";
}
private void PlanMonsters(UsdTable t, ImportPlan plan)
{
foreach (var row in t.Rows)
{
string name = t.Get(row, "MonsterName", "Name").Trim();
if (name.Length == 0) continue;
var rule = new MonsterRule
{
Name = name,
Priority = int.TryParse(t.Get(row, "AttackPriority", "Priority"), out int pri) ? Math.Max(0, pri) : 1,
DamageType = MapElement(t.Get(row, "DamageType")) ?? "Auto",
ExVuln = MapElement(t.Get(row, "SecondaryVuln", "ExtraVuln")) ?? "None",
PetDamage = MapElement(t.Get(row, "PetDamage")) ?? "PAuto",
UseRing = ParseBool(t.Get(row, "Ring")),
UseStreak = ParseBool(t.Get(row, "Streak")),
UseArc = ParseBool(t.Get(row, "Arc")),
Fester = ParseBool(t.Get(row, "Fester")),
Broadside = ParseBool(t.Get(row, "Broadside")),
GravityWell = ParseBool(t.Get(row, "GravityW", "GravityWell")),
Imperil = ParseBool(t.Get(row, "Imperil")),
Yield = ParseBool(t.Get(row, "Yield")),
Vuln = ParseBool(t.Get(row, "Vuln")),
};
var weapon = Resolve(ParseId(t.Get(row, "WeaponToUse", "Weapon")), t.Get(row, "WeaponName"));
if (weapon != null) rule.WeaponId = weapon.Id;
else if (t.Get(row, "WeaponName").Length > 0) plan.Notes.Add($"{name}: weapon '{t.Get(row, "WeaponName")}' not carried");
var off = Resolve(ParseId(t.Get(row, "SecondaryEquip", "Offhand")), t.Get(row, "OffhandName"));
if (off != null) rule.OffhandId = off.Id;
plan.Monsters.Add(rule);
}
}
private void PlanWeapons(UsdTable t, ImportPlan plan)
{
// The VT "shields" table (or any row whose item wields into the shield slot)
// becomes an off-hand Shield entry, never a main-hand weapon.
bool shieldTable = t.Name.Equals("shields", StringComparison.OrdinalIgnoreCase);
foreach (var row in t.Rows)
{
int id = ParseId(t.Get(row, "Object", "ObjectId", "Id"));
string name = t.Get(row, "Name").Trim();
var wo = Resolve(id, name);
if (wo == null) { if (name.Length > 0) plan.Notes.Add($"weapon '{name}' not carried"); continue; }
if (plan.Weapons.Any(w => w.Id == wo.Id)) continue;
bool isShield = shieldTable || RynthCore.Plugin.RynthAi.CombatManager.IsShieldItem(wo);
string element = BitsToElement(wo.Values(LongValueKey.DamageType, 0)) ?? "Slash";
plan.Weapons.Add(new ItemRule
{
Id = wo.Id,
Name = wo.Name,
Action = isShield ? ItemRule.ShieldAction : ItemRule.WeaponAction,
Element = element,
});
}
}
private void PlanConsumables(UsdTable t, ImportPlan plan, string? forceType)
{
foreach (var row in t.Rows)
{
int id = ParseId(t.Get(row, "Object", "ObjectId", "Id"));
string name = t.Get(row, "Name").Trim();
var wo = Resolve(id, name);
if (wo == null) { if (name.Length > 0) plan.Notes.Add($"item '{name}' not carried"); continue; }
if (wo.ObjectClass is AcObjectClass.MeleeWeapon or AcObjectClass.MissileWeapon or AcObjectClass.WandStaffOrb) continue;
if (plan.Consumables.Any(c => c.Id == wo.Id)) continue;
plan.Consumables.Add(new ConsumableRule { Id = wo.Id, Name = wo.Name, Type = forceType ?? ConsumableType(wo.Name) });
}
}
/// <summary>Writes the previewed rules into the live settings and saves them.</summary>
public void Apply()
{
var plan = _plan;
var s = _ctx.Settings;
if (plan == null || s == null) { _status = "Nothing to apply."; return; }
foreach (var m in plan.Monsters)
{
s.MonsterRules.RemoveAll(r => r.Name.Equals(m.Name, StringComparison.OrdinalIgnoreCase));
s.MonsterRules.Add(m);
}
foreach (var w in plan.Weapons)
{
s.ItemRules.RemoveAll(r => r.Id == w.Id);
s.ItemRules.Add(w);
}
foreach (var c in plan.Consumables)
{
s.ConsumableRules.RemoveAll(r => r.Id == c.Id);
s.ConsumableRules.Add(c);
}
_ctx.SaveCombatSettings?.Invoke();
_status = $"Imported {plan.Monsters.Count} monsters, {plan.Weapons.Count} weapons, {plan.Consumables.Count} consumables.";
_ctx.Chat("[Mini Remote] " + _status);
_plan = null;
}
// ── UI (render thread) ──────────────────────────────────────────────────
public void Render()
{
ImGui.TextColored(LegacyDashboardRenderer.ColTeal, "Import VirindiTank settings (.usd)");
ImGui.SetNextItemWidth(320);
ImGui.InputTextWithHint("##usdpath", @"full path or file name in C:\Games\VirindiPlugins\VirindiTank", ref _pathInput, 260u);
ImGui.SameLine();
string p = _pathInput;
if (ImGui.SmallButton("Preview")) _ctx.Post(() => Preview(p));
var plan = _plan;
if (plan != null)
{
ImGui.TextUnformatted($"{plan.Monsters.Count} monster rules, {plan.Weapons.Count} weapons, {plan.Consumables.Count} consumables");
if (ImGui.TreeNode("Preview details"))
{
foreach (var m in plan.Monsters.Take(50)) ImGui.BulletText($"Monster {m.Name} [{m.DamageType}] pri {m.Priority}");
foreach (var w in plan.Weapons) ImGui.BulletText($"Weapon {w.Name} [{w.Element}]");
foreach (var c in plan.Consumables) ImGui.BulletText($"{c.Type}: {c.Name}");
foreach (var n in plan.Notes.Take(30)) ImGui.TextColored(LegacyDashboardRenderer.ColAmber, n);
ImGui.TreePop();
}
if (ImGui.Button("Apply import..."))
_ctx.Confirm("Import VTank settings",
$"Write these rules into the current RynthAi profile?\nRules with the same monster name / item id are replaced.",
Apply, "Import");
}
if (_status.Length > 0) ImGui.TextWrapped(_status);
}
}

View file

@ -0,0 +1,129 @@
// ServerFeatureGate.cs — Which worlds get the ILT / infinite-attribute features.
//
// One gate for everything ILT-shaped: the ILT Hub and Mini Remote, the Skills panel's
// Progression planners and the attribute raiser. A world is "on" when:
// * its name matches one of the server patterns in Settings > Misc (FeatureServerNames,
// '*' wildcard, case-insensitive; defaults cover InfiniteLeaftide), or
// * the manual override is ticked (Settings > Misc ForceServerFeatures, or the older
// per-character ILT Hub "Treat this world as ILT" / "/ra hub force on").
// The gate only decides whether RynthAi ASKS the server; each feature still follows the
// server's own report (IltServerOptions bits), so a shard with /xp off keeps the raiser off.
using System;
using System.Collections.Generic;
using System.Linq;
using RynthCore.Plugin.RynthAi.LegacyUi;
namespace RynthCore.Plugin.RynthAi.IltHub;
internal static class ServerFeatureGate
{
/// <summary>Patterns a fresh profile starts with (the names the old hard-coded check accepted).</summary>
public static readonly string[] DefaultServerNames = { "InfiniteLeaftide", "*Leaftide*" };
/// <summary>World name of the current session; set by RynthAiPlugin (empty before login).</summary>
public static Func<string>? WorldNameProvider;
/// <summary>The per-character ILT Hub override (ilt-hub.json); set by the Hub while it exists.</summary>
public static Func<bool>? HubForceProvider;
public static string CurrentWorld
{
get
{
try { return (WorldNameProvider?.Invoke() ?? string.Empty).Trim(); }
catch { return string.Empty; }
}
}
/// <summary>The patterns in force: the profile's list, or the defaults when there is no profile yet.</summary>
public static IReadOnlyList<string> Patterns(LegacyUiSettings? settings)
=> settings?.FeatureServerNames ?? (IReadOnlyList<string>)DefaultServerNames;
/// <summary>True when <paramref name="world"/> matches one of <paramref name="patterns"/>.</summary>
public static bool NameMatches(string world, IEnumerable<string>? patterns, out string matched)
{
matched = string.Empty;
if (string.IsNullOrWhiteSpace(world) || patterns == null) return false;
foreach (string p in patterns)
{
if (string.IsNullOrWhiteSpace(p)) continue;
if (!Matches(world.Trim(), p.Trim())) continue;
matched = p.Trim();
return true;
}
return false;
}
/// <summary>Case-insensitive match where '*' stands for any run of characters (anywhere in the pattern).</summary>
public static bool Matches(string text, string pattern)
{
if (pattern.Length == 0) return false;
if (!pattern.Contains('*')) return text.Equals(pattern, StringComparison.OrdinalIgnoreCase);
string[] parts = pattern.Split('*');
int pos = 0;
for (int i = 0; i < parts.Length; i++)
{
string part = parts[i];
if (part.Length == 0) continue;
if (i == 0)
{
if (!text.StartsWith(part, StringComparison.OrdinalIgnoreCase)) return false;
pos = part.Length;
continue;
}
if (i == parts.Length - 1)
return text.Length - pos >= part.Length && text.EndsWith(part, StringComparison.OrdinalIgnoreCase);
int at = text.IndexOf(part, pos, StringComparison.OrdinalIgnoreCase);
if (at < 0) return false;
pos = at + part.Length;
}
return true;
}
/// <summary>Is the override on (Settings > Misc, or the per-character Hub checkbox)?</summary>
public static bool ForceOn(LegacyUiSettings? settings)
{
if (settings?.ForceServerFeatures == true) return true;
try { return HubForceProvider?.Invoke() == true; }
catch { return false; }
}
/// <summary>The gate itself.</summary>
public static bool IsEnabled(string world, LegacyUiSettings? settings)
=> ForceOn(settings) || NameMatches(world, Patterns(settings), out _);
/// <summary>"InfiniteLeaftide, *Leaftide*" → trimmed, de-duplicated list (case-insensitive).</summary>
public static List<string> ParseList(string? text)
{
var list = new List<string>();
if (string.IsNullOrWhiteSpace(text)) return list;
foreach (string raw in text.Split(new[] { ',', ';', '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries))
{
string p = raw.Trim();
if (p.Length > 0 && !list.Contains(p, StringComparer.OrdinalIgnoreCase)) list.Add(p);
}
return list;
}
public static string FormatList(IEnumerable<string>? patterns)
=> patterns == null ? string.Empty : string.Join(", ", patterns.Where(p => !string.IsNullOrWhiteSpace(p)));
/// <summary>One status line for Settings > Misc: the world, whether the features are on, and why.</summary>
public static string Describe(LegacyUiSettings? settings)
{
string world = CurrentWorld;
string shown = world.Length > 0 ? $"'{world}'" : "(not logged in)";
if (settings?.ForceServerFeatures == true)
return $"This world {shown}: ON - manual override.";
if (NameMatches(world, Patterns(settings), out string matched))
return $"This world {shown}: ON - matches '{matched}'.";
bool hubForce;
try { hubForce = HubForceProvider?.Invoke() == true; } catch { hubForce = false; }
if (hubForce)
return $"This world {shown}: ON - the Mini Remote's \"Treat this world as ILT\" override.";
return world.Length > 0
? $"This world {shown}: OFF - not in the list. Add it, or tick the override."
: "This world: not logged in yet.";
}
}

View file

@ -0,0 +1,69 @@
// ImGuiNativeBinding.cs - Binds ImGui.NET's "cimgui" P/Invokes to the cimgui module the
// engine already loaded.
//
// The engine ships its own build as RynthCore.cimgui.dll. Without this resolver, Windows
// resolves "cimgui" to a separate cimgui.dll: a second ImGui instance whose windows (ILT Hub,
// Pets, Quests, Mini Remote, Item HUD) are built but never reach the engine's draw data.
using System;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Threading;
using ImGuiNET;
namespace RynthCore.Plugin.RynthAi;
internal static class ImGuiNativeBinding
{
private const string EngineModule = "RynthCore.cimgui.dll";
private const string LegacyModule = "cimgui.dll";
private static int _configured; // 1 once the resolver is registered (survives DLL-copy reuse)
private static int _resolvedLogged;
/// <summary>
/// Registers the resolver. Call before the first ImGui call (Initialize). The resolver can be
/// set only once per assembly, so later calls (a reused plugin DLL copy) are no-ops.
/// </summary>
public static void Ensure()
{
if (Interlocked.Exchange(ref _configured, 1) != 0) return;
try
{
NativeLibrary.SetDllImportResolver(typeof(ImGui).Assembly, Resolve);
RynthLog.Write(LogCat.UI, "[ImGui] native resolver registered (prefers the engine's " + EngineModule + ").");
}
catch (InvalidOperationException)
{
// Already registered by an earlier instance in this process.
}
catch (Exception ex)
{
RynthLog.Exception(LogCat.UI, ex, "ImGuiNativeBinding.Ensure");
}
}
/// <summary>Runs on the first cimgui P/Invoke: the engine's module, else whatever cimgui.dll is loaded.</summary>
private static IntPtr Resolve(string libraryName, Assembly assembly, DllImportSearchPath? searchPath)
{
if (!string.Equals(libraryName, "cimgui", StringComparison.OrdinalIgnoreCase) &&
!string.Equals(libraryName, LegacyModule, StringComparison.OrdinalIgnoreCase))
return IntPtr.Zero;
string bound = EngineModule;
IntPtr module = GetModuleHandleA(EngineModule);
if (module == IntPtr.Zero)
{
bound = LegacyModule;
module = GetModuleHandleA(LegacyModule);
}
if (Interlocked.Exchange(ref _resolvedLogged, 1) == 0)
RynthLog.Write(LogCat.UI, module != IntPtr.Zero
? $"[ImGui] cimgui bound to loaded {bound} (0x{module.ToInt64():X})."
: "[ImGui] no loaded cimgui module found; falling back to the default DLL search.");
return module; // IntPtr.Zero = default resolution
}
[DllImport("kernel32.dll", CharSet = CharSet.Ansi, ExactSpelling = true)]
private static extern IntPtr GetModuleHandleA(string lpModuleName);
}

View file

@ -1,318 +0,0 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using RynthCore.Loot.Editing;
using RynthCore.Plugin.RynthAi.CreatureData;
namespace RynthCore.Plugin.RynthAi.ItemInfo;
/// <summary>One item's appraisal values, as <see cref="ItemInfoText"/> reads them.</summary>
internal interface IItemInfoSource
{
/// <summary>The name the client shows ("" when unknown).</summary>
string Name { get; }
bool TryInt(uint key, out int value);
bool TryFloat(uint key, out double value);
/// <summary>The item's spells (empty when none or not appraised).</summary>
IReadOnlyList<int> SpellIds { get; }
}
/// <summary>
/// /ra iteminfo's text: one item on one chat line, in the spirit of Mag-Tools' item info
/// (name, type, set, armor, ratings, damage and mods, imbues, slayer, tinks, spells by name,
/// wield and activation requirements, craft, material, value and burden). A field the
/// appraisal doesn't carry is left out. Pure: no host calls, so the host tests feed it a
/// fake source.
/// </summary>
internal static class ItemInfoText
{
// STypeInt (AC / ACE PropertyInt numbering; the names in Meta/PropertyNames.cs).
internal const uint IntItemType = 1, IntEncumbrance = 5, IntStackSize = 12, IntRareId = 17, IntValue = 19,
IntArmorLevel = 28, IntBonded = 33, IntDamage = 44, IntDamageType = 45, IntWeaponSkill = 48,
IntWeaponTime = 49, IntWorkmanship = 105, IntSpellcraft = 106, IntCurMana = 107, IntMaxMana = 108,
IntItemDifficulty = 109, IntAllegianceRankLimit = 110, IntAttuned = 114, IntSkillLevelLimit = 115,
IntMaterial = 131, IntWieldReq = 158, IntWieldSkill = 159, IntWieldDiff = 160, IntSlayerType = 166,
IntTinks = 171, IntImbued = 179, IntElementalBonus = 204, IntSetId = 265, IntWieldReq2 = 270,
IntWieldSkill2 = 271, IntWieldDiff2 = 272, IntItemMaxLevel = 319;
// STypeFloat (ACE PropertyFloat numbering).
internal const uint FloatDamageVariance = 22, FloatMeleeDefense = 29, FloatWeaponOffense = 62, FloatDamageMod = 63,
FloatManaConversion = 144, FloatMissileDefense = 149, FloatMagicDefense = 150, FloatElementalDamage = 152,
FloatCriticalMultiplier = 136, FloatCriticalFrequency = 147;
/// <summary>Gear ratings (STypeInt 370-389) and their short tags, in print order.</summary>
internal static readonly (uint Key, string Tag)[] Ratings =
{
(370, "D"), (371, "DR"), (372, "C"), (373, "CR"), (374, "CD"), (375, "CDR"),
(376, "HB"), (379, "Vit"), (377, "NR"), (378, "LR"), (388, "OP"), (389, "OPR"),
(383, "PvP D"), (384, "PvP DR"),
};
// ItemType flags (STypeInt 1), most specific first.
private static readonly (uint Flag, string Name)[] Types =
{
(0x00040000, "Promissory Note"), (0x00080000, "Mana Stone"), (0x00001000, "Spell Component"),
(0x00000800, "Gem"), (0x00004000, "Key"), (0x40000000, "Salvage"), (0x20000000, "Tinkering Tool"),
(0x00000200, "Container"), (0x00008000, "Caster"), (0x00000100, "Missile Weapon"),
(0x00000001, "Melee Weapon"), (0x00000002, "Armor"), (0x00000004, "Clothing"), (0x00000008, "Jewelry"),
(0x00000020, "Food"), (0x00000040, "Money"), (0x00002000, "Writable"), (0x00000080, "Misc"),
};
// ImbuedEffect flags (STypeInt 179).
private static readonly (uint Flag, string Name)[] Imbues =
{
(0x0001, "Critical Strike"), (0x0002, "Crippling Blow"), (0x0004, "Armor Rending"),
(0x0008, "Slash Rending"), (0x0010, "Pierce Rending"), (0x0020, "Bludgeon Rending"),
(0x0040, "Acid Rending"), (0x0080, "Cold Rending"), (0x0100, "Lightning Rending"),
(0x0200, "Fire Rending"), (0x0400, "Melee Defense"), (0x0800, "Missile Defense"),
(0x1000, "Magic Defense"), (0x4000, "Nether Rending"),
};
// Equipment sets (STypeInt 265) whose ids are certain: the loot armor sets and Aetheria.
private static readonly Dictionary<int, string> Sets = new()
{
[13] = "Soldier's", [14] = "Adept's", [15] = "Archer's", [16] = "Defender's", [17] = "Tinker's",
[18] = "Crafter's", [19] = "Hearty", [20] = "Dexterous", [21] = "Wise", [22] = "Swift",
[23] = "Hardened", [24] = "Reinforced", [25] = "Interlocking", [26] = "Flame Proof",
[27] = "Acid Proof", [28] = "Cold Proof", [29] = "Lightning Proof",
[35] = "Aetheria: Defense", [36] = "Aetheria: Destruction", [37] = "Aetheria: Fury",
[38] = "Aetheria: Growth", [39] = "Aetheria: Vigor",
};
// Attributes and vitals for attribute/vital wield requirements (ACE PropertyAttribute / PropertyAttribute2nd).
private static readonly string[] Attributes = { "", "Strength", "Endurance", "Quickness", "Coordination", "Focus", "Self" };
private static readonly string[] Vitals = { "", "Max Health", "Health", "Max Stamina", "Stamina", "Max Mana", "Mana" };
private static readonly CultureInfo Inv = CultureInfo.InvariantCulture;
/// <summary>
/// The item on one line. <paramref name="spellName"/> names a spell id (the plugin's
/// spell table). <paramref name="identified"/> false adds a note that the server never
/// answered the ID, so only what the client already knew is shown.
/// </summary>
public static string Describe(IItemInfoSource item, Func<int, string> spellName, bool identified = true)
{
var parts = new List<string>(24);
int type = Int(item, IntItemType);
// Name, with the material in front the way the game names loot ("Gold Ring").
string name = item.Name.Trim();
int material = Int(item, IntMaterial);
string full = WeaponNames.Full(name, material);
if (full.Length == 0) full = "(unnamed item)";
string typeName = TypeName(type);
int stack = Int(item, IntStackSize);
var head = new StringBuilder(full);
if (stack > 1) head.Append(" x").Append(stack.ToString("N0", Inv));
if (typeName.Length > 0) head.Append(" (").Append(typeName).Append(')');
parts.Add(head.ToString());
if (Int(item, IntSetId) is int set and > 0)
parts.Add((Sets.TryGetValue(set, out string? setName) ? setName : "Set " + set) + " Set");
if (item.TryInt(IntArmorLevel, out int al) && (al > 0 || (type & 0x2) != 0))
parts.Add("AL " + al.ToString(Inv));
string ratings = RatingText(item);
if (ratings.Length > 0) parts.Add(ratings);
AddWeapon(item, type, parts);
string imbues = ImbueText(Int(item, IntImbued));
if (imbues.Length > 0) parts.Add(imbues);
if (Int(item, IntSlayerType) is int slayer and > 0)
parts.Add(CreatureTypeNames.Name(slayer) + " Slayer");
if (item.TryInt(IntTinks, out int tinks) && tinks > 0)
parts.Add("Tinks " + tinks.ToString(Inv));
string spells = SpellText(item.SpellIds, spellName);
if (spells.Length > 0) parts.Add(spells);
string wield = WieldText(item, IntWieldReq, IntWieldSkill, IntWieldDiff);
if (wield.Length > 0) parts.Add(wield);
string wield2 = WieldText(item, IntWieldReq2, IntWieldSkill2, IntWieldDiff2);
if (wield2.Length > 0) parts.Add(wield2);
if (Int(item, IntSkillLevelLimit) is int skillLimit and > 0) parts.Add("Skill " + skillLimit.ToString(Inv) + " to activate");
if (Int(item, IntAllegianceRankLimit) is int rank and > 0) parts.Add("Rank " + rank.ToString(Inv));
if (Int(item, IntItemDifficulty) is int diff and > 0) parts.Add("Diff " + diff.ToString(Inv));
if (Int(item, IntSpellcraft) is int spellcraft and > 0) parts.Add("Spellcraft " + spellcraft.ToString(Inv));
if (item.TryInt(IntMaxMana, out int maxMana) && maxMana > 0)
parts.Add("Mana " + (item.TryInt(IntCurMana, out int cur) ? cur.ToString(Inv) + "/" : "") + maxMana.ToString(Inv));
if (Int(item, IntItemMaxLevel) is int maxLevel and > 0) parts.Add("Max Level " + maxLevel.ToString(Inv));
if (item.TryInt(IntWorkmanship, out int craft) && craft > 0) parts.Add("Craft " + craft.ToString(Inv));
string matName = WeaponNames.Material(material);
if (matName.Length > 0) parts.Add("Mat " + matName);
if (Int(item, IntBonded) == 1) parts.Add("Bonded");
if (Int(item, IntAttuned) == 1) parts.Add("Attuned");
if (Int(item, IntRareId) is int rare and > 0) parts.Add("Rare #" + rare.ToString(Inv));
if (item.TryInt(IntValue, out int value)) parts.Add("Value " + value.ToString("N0", Inv));
if (item.TryInt(IntEncumbrance, out int burden)) parts.Add("BU " + burden.ToString("N0", Inv));
if (!identified) parts.Add("(not identified: no reply from the server)");
return string.Join(", ", parts);
}
private static int Int(IItemInfoSource item, uint key) => item.TryInt(key, out int v) ? v : 0;
/// <summary>The item's kind from its ItemType flags ("" when none is set).</summary>
internal static string TypeName(int itemType)
{
uint t = unchecked((uint)itemType);
foreach (var (flag, n) in Types)
if ((t & flag) != 0) return n;
return "";
}
/// <summary>"[D3 CD2 CDR1]" for the gear ratings that are set; "" for none.</summary>
internal static string RatingText(IItemInfoSource item)
{
var sb = new StringBuilder();
foreach (var (key, tag) in Ratings)
{
if (!item.TryInt(key, out int r) || r <= 0) continue;
sb.Append(sb.Length == 0 ? "[" : " ").Append(tag).Append(r.ToString(Inv));
}
return sb.Length == 0 ? "" : sb.Append(']').ToString();
}
private static void AddWeapon(IItemInfoSource item, int type, List<string> parts)
{
uint t = unchecked((uint)type);
bool melee = (t & 0x1) != 0, missile = (t & 0x100) != 0, caster = (t & 0x8000) != 0;
bool weapon = melee || missile || caster;
if (Int(item, IntWeaponSkill) is int skill and > 0 && weapon)
parts.Add(SkillName(skill));
int dmgType = Int(item, IntDamageType);
if (item.TryInt(IntDamage, out int max) && max > 0)
{
string dmg = "Dmg " + max.ToString(Inv);
if (item.TryFloat(FloatDamageVariance, out double variance) && variance > 0 && variance < 1)
{
int min = (int)Math.Round(max * (1.0 - variance), MidpointRounding.AwayFromZero);
dmg = $"Dmg {min.ToString(Inv)}-{max.ToString(Inv)}";
}
string element = DamageTypeName(dmgType);
if (element.Length > 0) dmg += " " + element;
parts.Add(dmg);
}
else if (weapon && dmgType > 0)
{
string element = DamageTypeName(dmgType);
if (element.Length > 0) parts.Add(element);
}
if (Int(item, IntElementalBonus) is int elemBonus and > 0) parts.Add("+" + elemBonus.ToString(Inv) + " elemental dmg");
if (weapon && item.TryInt(IntWeaponTime, out int speed) && speed > 0) parts.Add("Speed " + speed.ToString(Inv));
// Crushing Blow and Biting Strike, the way the client's appraisal names them (shown as
// SilentKelpie's fork shows them, rynth/RynthSuite PR #3). ACE deals a crit as damage x
// (1 + CriticalMultiplier) (DamageEvent), so 2.66 reads "Crushing Blow 3.66x"; 1.0 is an
// ordinary crit. CriticalFrequency is the weapon's own crit chance (default 10%, 5% casters).
if (weapon && item.TryFloat(FloatCriticalMultiplier, out double critMult) && critMult > 1.0)
parts.Add("Crushing Blow " + (1.0 + critMult).ToString("0.##", Inv) + "x");
if (weapon && item.TryFloat(FloatCriticalFrequency, out double critFreq) && critFreq > 0 && critFreq < 1)
parts.Add("Biting Strike " + (critFreq * 100.0).ToString("0.#", Inv) + "%");
// Modifiers: 1.18 = +18%. Missile launchers' damage mod and casters' elemental mod too.
var mods = new List<string>(6);
AddPercent(item, FloatWeaponOffense, "atk", mods, weapon);
if (missile) AddPercent(item, FloatDamageMod, "dmg", mods, true);
if (caster) AddPercent(item, FloatElementalDamage, "vs monsters", mods, true);
AddPercent(item, FloatMeleeDefense, "md", mods, weapon);
AddPercent(item, FloatMissileDefense, "mid", mods, weapon);
AddPercent(item, FloatMagicDefense, "mgd", mods, weapon);
AddPercent(item, FloatManaConversion, "mana c", mods, true);
if (mods.Count > 0) parts.Add("(" + string.Join(", ", mods) + ")");
}
private static void AddPercent(IItemInfoSource item, uint key, string label, List<string> mods, bool allowed)
{
if (!allowed || !item.TryFloat(key, out double v) || double.IsNaN(v)) return;
// Multipliers (attack, defense, damage) are stored as 1.xx; mana conversion as 0.xx.
double pct = key == FloatManaConversion ? v * 100.0 : (v - 1.0) * 100.0;
int rounded = (int)Math.Round(pct, MidpointRounding.AwayFromZero);
if (rounded == 0) return;
mods.Add((rounded > 0 ? "+" : "") + rounded.ToString(Inv) + "% " + label);
}
/// <summary>"Crippling Blow, Fire Rending" for the imbue flags; "" for none.</summary>
internal static string ImbueText(int flags)
{
if (flags == 0) return "";
uint f = unchecked((uint)flags);
var names = new List<string>(2);
foreach (var (flag, n) in Imbues)
if ((f & flag) != 0) names.Add(n);
return string.Join(", ", names);
}
/// <summary>"Spells: A, B, C" by name, in the item's order, each once; "" for none.</summary>
internal static string SpellText(IReadOnlyList<int> spellIds, Func<int, string> spellName)
{
if (spellIds.Count == 0) return "";
var seen = new HashSet<int>();
var names = new List<string>(spellIds.Count);
foreach (int id in spellIds)
{
if (id <= 0 || !seen.Add(id)) continue;
string n = spellName(id);
names.Add(string.IsNullOrWhiteSpace(n) ? "spell " + id.ToString(Inv) : n);
}
return names.Count == 0 ? "" : "Spells: " + string.Join(", ", names);
}
/// <summary>One wield requirement ("Wield Lvl 180", "Heavy Weapons 375 to wield"); "" for none.</summary>
internal static string WieldText(IItemInfoSource item, uint reqKey, uint skillKey, uint diffKey)
{
int req = Int(item, reqKey);
if (req <= 0) return "";
int skill = Int(item, skillKey);
int diff = Int(item, diffKey);
string d = diff.ToString(Inv);
return req switch
{
1 => $"{SkillName(skill)} {d} to wield",
2 => $"Base {SkillName(skill)} {d} to wield",
3 => $"{Pick(Attributes, skill, "Attribute")} {d} to wield",
4 => $"Base {Pick(Attributes, skill, "Attribute")} {d} to wield",
5 => $"{Pick(Vitals, skill, "Vital")} {d} to wield",
6 => $"Base {Pick(Vitals, skill, "Vital")} {d} to wield",
7 => $"Wield Lvl {d}",
8 => $"{(diff >= 3 ? "Specialized" : "Trained")} {SkillName(skill)} to wield",
12 => $"Heritage {d} to wield",
_ => $"Wield requirement {req.ToString(Inv)} ({skill.ToString(Inv)}, {d})",
};
}
private static string Pick(string[] names, int i, string fallback) =>
i > 0 && i < names.Length ? names[i] : $"{fallback} {i.ToString(Inv)}";
/// <summary>AC's skill name for a skill id ("skill N" when unknown).</summary>
internal static string SkillName(int id)
{
foreach (var (sid, n) in LootRuleText.Skills)
if (sid == id) return n;
return "skill " + id.ToString(Inv);
}
/// <summary>The damage type's name ("Slashing/Piercing" etc.); "" for none.</summary>
internal static string DamageTypeName(int flags)
{
if (flags <= 0) return "";
foreach (var (id, n) in LootRuleText.DamageTypes)
if (id == flags) return n;
// Other combinations: the single flags joined.
var names = new List<string>(3);
foreach (var (id, n) in LootRuleText.DamageTypes)
if (id > 0 && (id & (id - 1)) == 0 && (flags & id) != 0) names.Add(n);
return string.Join("/", names);
}
}

View file

@ -0,0 +1,795 @@
// MagItemDescriber.cs — one-line "Mag-style" item info (Mag-Tools ItemInfo / UtilityBelt ub-IT ItemInfo).
//
// Gold Ornate Long Sword (Slash Sword), Noble Relic Set, CS, Undead Slayer, Tinks 4,
// Applied: Steel x2, 152-236, 0.35v, +18%a, +12%md, Legendary Blood Thirst, Wield Lvl 180,
// Heavy Weapons 375, Diff 270, Craft 8, [D 3, CD 2]
//
// The same fields can also print as the pet-roster layout (IltPetStats: identity line, stats
// line, ratings/requirements line), plus a spells line:
//
// Gold Ornate Long Sword (Slash Sword), Noble Relic Set, Tinks 4, Applied: Steel x2, Craft 8
// CS, Undead Slayer, 152-236, 0.35v, +18%a, +12%md
// [D 3, CD 2] Wield Lvl 180, Heavy Weapons 375, Diff 270
// Spells: Legendary Blood Thirst
//
// Values follow what the ACECustom appraisal panel shows: the low damage end is rounded like the
// client, Crushing Blow is the dealt multiplier (1 + CriticalMultiplier), and imbue strengths,
// the T11 weapon / gear grades, property slots, procs, zone modifiers and item-aug wield gates
// come from the description text because the server keeps those properties off the wire; the
// T11 tier and weapon quality roll are real properties (ZcTier, WeaponAugScale*):
//
// Flaming Quarter Staff (Fire Staff), T16, Quality 1000, Props 2/5, Grade S (100%), Craft 9
// FireRend +176%, Crushing Blow 3.66x, 1790-2069, 0.135v, +20%a, +20%md
// [CD 24] Wield 2,000 Item Augs
//
// Field order and per-class gating follow ub-IT (Tools/ItemInfo.cs ItemDescriptions.ToString,
// Lib/ItemDescribeMagShorthand.cs, Lib/ItemInfoHelper/ItemIdentifyFieldSet.cs); labels and the
// spell filter follow Mag-Tools. All ids are raw ACE properties (RynthCore reads CBaseQualities by
// STypeInt/STypeFloat/STypeString id — not Decal's remapped LongValueKey/DoubleValueKey numbers).
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using System.Text.RegularExpressions;
using RynthCore.Loot;
using RynthCore.Loot.T11;
namespace RynthCore.Plugin.RynthAi.ItemInfo;
/// <summary>Property reads for one item. Implemented over the live object cache (see
/// <see cref="CacheItemPropertySource"/>); a missing property returns false / empty.</summary>
internal interface IItemPropertySource
{
string Name { get; }
AcObjectClass ObjectClass { get; }
bool TryGetInt(uint stype, out int value);
bool TryGetDouble(uint stype, out double value);
string GetString(uint stype);
/// <summary>Spell ids on the item (inscribed + cantrips), unsorted.</summary>
IReadOnlyList<int> SpellIds { get; }
}
/// <summary>Per-call output options, snapshotted from <see cref="MagItemInfoSettings"/>.</summary>
internal readonly record struct MagItemInfoOptions(
MagItemInfoField Hidden, int HiddenRatings, bool ShowValueAndBurden, bool AllSpells, int MaxListedSpells)
{
/// <summary>Everything shown, Mag spell filter — used when no settings are loaded yet.</summary>
public static readonly MagItemInfoOptions Default = new(MagItemInfoField.None, 0, false, false, 26);
public static MagItemInfoOptions From(MagItemInfoSettings? s) => s == null
? Default
: new((MagItemInfoField)s.HiddenFields, s.HiddenRatings, s.ShowValueAndBurden,
s.SpellMode == MagItemInfoSettings.SpellModeAll, s.MaxListedSpells);
public bool Shows(MagItemInfoField f) => (Hidden & f) == 0;
}
/// <summary>Which pet-style line a field lands on (<see cref="MagItemDescription.ToPetLines"/>).</summary>
internal enum MagItemSection
{
/// <summary>Line 1 after the name: set, AL, tinks, applied, craft, keyring.</summary>
Identity,
/// <summary>Line 2: imbues, slayer, damage, attack/defense/mana-conversion, protections.</summary>
Combat,
/// <summary>Line 3 lead: the "[D 3, CD 2]" cluster.</summary>
Ratings,
/// <summary>Line 3 tail: wield / activation / difficulty, value and burden.</summary>
Requirements,
/// <summary>Line 4: spell names.</summary>
Spells,
}
/// <summary>
/// One described item: the title plus fields tagged with their section, kept in Mag print order
/// so <see cref="ToOneLine"/> reproduces the classic line exactly.
/// </summary>
internal sealed class MagItemDescription
{
/// <summary>"[Material ]Name[ (DamageType Mastery)]".</summary>
public string Title = string.Empty;
public readonly List<(MagItemSection Section, string Text)> Segments = new();
public void Add(MagItemSection section, string text)
{
if (!string.IsNullOrEmpty(text)) Segments.Add((section, text));
}
/// <summary>Classic Mag one-liner: title, then every field comma-separated.</summary>
public string ToOneLine()
{
var sb = new StringBuilder(Title, 256);
foreach (var (_, text) in Segments) sb.Append(", ").Append(text);
return sb.ToString();
}
/// <summary>
/// Pet-roster layout: line 1 is always present; empty stat / requirement / spell lines are
/// dropped so plain armor stays short.
/// </summary>
public List<string> ToPetLines()
{
var lines = new List<string>(4);
var identity = new StringBuilder(Title);
foreach (string t in Section(MagItemSection.Identity)) identity.Append(", ").Append(t);
lines.Add(identity.ToString());
string combat = string.Join(", ", Section(MagItemSection.Combat));
if (combat.Length > 0) lines.Add(combat);
// Like the pet roster's third line: ratings first, then the rest two-space separated.
var tail = new List<string>(2);
string ratings = string.Join(", ", Section(MagItemSection.Ratings));
if (ratings.Length > 0) tail.Add(ratings);
string reqs = string.Join(", ", Section(MagItemSection.Requirements));
if (reqs.Length > 0) tail.Add(reqs);
if (tail.Count > 0) lines.Add(string.Join(" ", tail));
var spells = Section(MagItemSection.Spells);
if (spells.Count > 0)
{
// The verbose list is a single pre-labelled "Spells: a; b" segment.
lines.Add(spells.Count == 1 && spells[0].StartsWith("Spells:", StringComparison.Ordinal)
? spells[0]
: "Spells: " + string.Join(", ", spells));
}
return lines;
}
private List<string> Section(MagItemSection section)
{
var list = new List<string>();
foreach (var (s, text) in Segments)
if (s == section) list.Add(text);
return list;
}
}
/// <summary>Builds the Mag-style item info line.</summary>
internal static class MagItemDescriber
{
// ── ACE PropertyInt ids ──────────────────────────────────────────────────
private const uint IntBurden = 5; // EncumbranceVal
private const uint IntValue = 19;
private const uint IntArmorLevel = 28;
private const uint IntResistMagic = 36; // >= 9999 = unenchantable
private const uint IntMaxDamage = 44; // Damage
private const uint IntDamageType = 45;
private const uint IntAttackType = 47;
private const uint IntStructure = 92; // keyring uses remaining
private const uint IntWorkmanship = 105;
private const uint IntItemDifficulty = 109; // arcane lore requirement ("Diff")
private const uint IntActivationLevel = 115; // ItemSkillLevelLimit
private const uint IntMaterial = 131;
private const uint IntWieldReq = 158;
private const uint IntWieldSkill = 159;
private const uint IntWieldValue = 160;
private const uint IntSlayerCreature = 166;
private const uint IntNumItemsInMaterial = 170; // salvage: workmanship = 105 / 170
private const uint IntTinks = 171;
private const uint IntActivationSkill = 176; // AppraisalItemSkill
private const uint IntImbued = 179; // ImbuedEffect (+ 303..306 for 2..5)
private const uint IntNumKeys = 193;
private const uint IntElementalBonus = 204;
private const uint IntEquipmentSet = 265;
private const uint IntWieldReq2 = 270;
private const uint IntWieldSkill2 = 271;
private const uint IntWieldValue2 = 272;
private const uint IntWeaponType = 353; // mastery
private const uint IntUseRequiresSkill = 366;
private const uint IntUseRequiresSkillLvl = 367;
private const uint IntUseRequiresSpec = 368;
private const uint IntUseRequiresLevel = 369;
private const uint IntSplitArrows = 9031; // ACECustom SplitArrowCount
// ── ACE PropertyFloat ids ────────────────────────────────────────────────
private const uint FloatArmorVsSlash = 13; // 13..19 = Slash/Pierce/Bludgeon/Cold/Fire/Acid/Electric
private const uint FloatVariance = 22;
private const uint FloatMaxVelocity = 26;
private const uint FloatMeleeDefense = 29; // WeaponDefense
private const uint FloatAttack = 62; // WeaponOffense
private const uint FloatDamageMod = 63;
private const uint FloatCritMultiplier = 136;
private const uint FloatManaConversion = 144;
private const uint FloatCritFrequency = 147;
private const uint FloatMissileDefense = 149;
private const uint FloatMagicDefense = 150;
private const uint FloatVsMonsters = 152; // ElementalDamageMod
private const uint FloatIgnoreArmor = 155; // armor cleaving
// ── ACE PropertyString ids ───────────────────────────────────────────────
private const uint StringUse = 14; // ACECustom: T11 armor/jewelry "Modifiers:" block
private const uint StringLongDesc = 16; // ACECustom: "Property Details:" lines (imbue strengths, grade, gates)
private const uint StringTinkerLog = 9007; // ACECustom: CSV of applied material ids
/// <summary>ACECustom's WieldRequirement.Int64Stat: the client gets it as text, never as properties.</summary>
private const int WieldReqInt64Stat = 13;
/// <summary>Gear ratings are small (1..~50). Anything above is a wrong key leaking through.</summary>
private const int MaxPlausibleRating = 200;
/// <summary>Class-specific fields (ub-IT ItemIdentifyFieldSet). Generic fields print for every class.</summary>
[Flags]
private enum Field
{
None = 0,
DamageType = 1 << 0,
CritStats = 1 << 1,
Splits = 1 << 2,
Cleaves = 1 << 3,
Slayer = 1 << 4,
Range = 1 << 5,
Damage = 1 << 6,
AttackBonus = 1 << 7,
MeleeDefense = 1 << 8,
MissileDefense = 1 << 9,
MagicDefense = 1 << 10,
ManaConversion = 1 << 11,
ArmorCleave = 1 << 12,
WeaponDefenses = MeleeDefense | MissileDefense | MagicDefense,
}
private static Field FieldsFor(AcObjectClass cls) => cls switch
{
AcObjectClass.MissileWeapon => Field.DamageType | Field.CritStats | Field.Splits | Field.Cleaves
| Field.Slayer | Field.Range | Field.Damage | Field.WeaponDefenses
| Field.ArmorCleave,
AcObjectClass.MeleeWeapon => Field.DamageType | Field.CritStats | Field.Cleaves | Field.Slayer
| Field.Damage | Field.AttackBonus | Field.WeaponDefenses
| Field.ArmorCleave,
AcObjectClass.WandStaffOrb => Field.DamageType | Field.CritStats | Field.Slayer | Field.Damage
| Field.WeaponDefenses | Field.ManaConversion,
AcObjectClass.Jewelry => Field.None,
// Armor / clothing / misc: keep Mag's generic bonus lines (shields roll %md etc.).
_ => Field.AttackBonus | Field.WeaponDefenses | Field.ManaConversion,
};
/// <summary>Full Mag-style line for one item (name first, comma-separated fields).</summary>
public static string Describe(IItemPropertySource item, MagItemInfoOptions options)
=> Build(item, options).ToOneLine();
/// <summary>Reads every enabled field once, tagged by section (one-line or pet-style output).</summary>
public static MagItemDescription Build(IItemPropertySource item, MagItemInfoOptions options)
{
var d = new MagItemDescription();
var sb = new StringBuilder(128); // title only
AcObjectClass cls = item.ObjectClass;
Field fields = FieldsFor(cls);
bool Has(Field f) => (fields & f) == f;
bool Show(MagItemInfoField f) => options.Shows(f);
int Int(uint id) => item.TryGetInt(id, out int v) ? v : 0;
double Dbl(uint id, double fallback) => item.TryGetDouble(id, out double v) ? v : fallback;
// ── Name: "[Material ]Name (DamageType Mastery)" ────────────────────────
int material = Int(IntMaterial);
if (material > 0 && Show(MagItemInfoField.Material))
{
string matName = MagItemInfoTables.Materials.TryGetValue(material, out string? m) ? m : $"material {material}";
// Loot names usually omit the material; don't double it when the name already starts with it.
if (!item.Name.StartsWith(matName, StringComparison.OrdinalIgnoreCase))
sb.Append(matName).Append(' ');
}
sb.Append(item.Name);
if (Has(Field.DamageType) && Show(MagItemInfoField.TypeMastery))
{
string dmgType = MagItemInfoTables.DamageTypeName(Int(IntDamageType));
int mastery = Int(IntWeaponType);
string masteryName = mastery > 0
? (MagItemInfoTables.Masteries.TryGetValue(mastery, out string? mn) ? mn : $"Unknown mastery {mastery}")
: string.Empty;
string inner = $"{dmgType} {masteryName}".Trim();
if (inner.Length > 0) sb.Append(" (").Append(inner).Append(')');
}
d.Title = sb.ToString();
const MagItemSection Id = MagItemSection.Identity, Cbt = MagItemSection.Combat, Req = MagItemSection.Requirements;
string I(int v) => v.ToString(CultureInfo.InvariantCulture);
// Text-only appraisal data (empty until the item has been IDed).
string longDesc = item.GetString(StringLongDesc);
var t11Server = new T11ServerProps(
Int(T11Catalog.PropZcTier),
Int(T11Catalog.PropWeaponAugScaleTier),
item.TryGetInt(T11Catalog.PropWeaponAugScaleQuality, out int quality) ? quality : -1);
T11ItemInfo t11 = T11ItemInfo.Parse(item.Name, longDesc, item.GetString(StringUse), t11Server);
// ── Set ─────────────────────────────────────────────────────────────────
int set = Int(IntEquipmentSet);
if (set > 0 && Show(MagItemInfoField.Set))
d.Add(Id, MagItemInfoTables.EquipmentSets.TryGetValue(set, out string? setName) ? setName : $"Unknown set {set}");
// ── T11 state: "T16, Gear B+ (4 lines), Props 3/5, Tainted" ───────────
if (t11.IsT11 && Show(MagItemInfoField.T11))
{
// "~" marks a tier estimated from the wield gates (older server, or not yet IDed).
d.Add(Id, t11.TierIsExact ? "T" + I(t11.Tier) : "~T" + I(t11.Tier));
if (t11.WeaponQuality >= 0) d.Add(Id, "Quality " + I(t11.WeaponQuality));
if (t11.GearGradeRank > 0)
d.Add(Id, t11.GearGradeLines > 0 ? $"Gear {t11.GearGrade} ({I(t11.GearGradeLines)} lines)" : $"Gear {t11.GearGrade}");
if (t11.PropertySlots >= 0)
d.Add(Id, t11.PropertySlotCap > 0 ? $"Props {I(t11.PropertySlots)}/{I(t11.PropertySlotCap)}" : $"Props {I(t11.PropertySlots)}");
if (t11.Tainted) d.Add(Id, "Tainted");
}
// ── Armor level ─────────────────────────────────────────────────────────
int al = Int(IntArmorLevel);
if (al > 0 && Show(MagItemInfoField.ArmorLevel)) d.Add(Id, "AL " + I(al));
// ── Imbues (ImbuedEffect 179 plus ImbuedEffect2..5 = 303..306) ─────────
if (Show(MagItemInfoField.Imbues))
d.Add(Cbt, ImbueLabels(Int(IntImbued) | Int(303) | Int(304) | Int(305) | Int(306), ImbueStrengths(longDesc)));
if (Has(Field.ArmorCleave) && Show(MagItemInfoField.ArmorCleave) && Dbl(FloatIgnoreArmor, 0) != 0)
d.Add(Cbt, "AC");
if (Has(Field.CritStats) && Show(MagItemInfoField.CritStats))
{
// A crit deals 1 + CriticalMultiplier; a stored 1.0 is a normal 2x crit, so ACE only
// calls it Crushing Blow above 1.0.
double critMult = Dbl(FloatCritMultiplier, 0);
if (critMult > 1) d.Add(Cbt, $"Crushing Blow {Fmt(critMult + 1)}x");
// Biting Strike replaces the base crit chance with this fraction.
double critFreq = Dbl(FloatCritFrequency, 0);
if (critFreq > 0) d.Add(Cbt, $"Biting Strike {Math.Round(critFreq * 100).ToString(CultureInfo.InvariantCulture)}%");
}
// T11 Cast on Strike procs: "Proc Force Arc 13%".
if (Show(MagItemInfoField.Imbues))
foreach (var (procName, chance) in t11.Procs)
d.Add(Cbt, $"Proc {procName} {Fmt(chance)}%");
if (Has(Field.Splits) && Show(MagItemInfoField.Splits))
{
int splits = Int(IntSplitArrows);
if (splits > 0) d.Add(Cbt, $"Splits ({I(splits)})");
}
if (Has(Field.Range) && Show(MagItemInfoField.Range))
{
int yards = MissileRangeYards(Dbl(FloatMaxVelocity, 0));
if (yards > 0) d.Add(Cbt, $"Range {I(yards)}yd");
}
if (Has(Field.Cleaves) && Show(MagItemInfoField.CleaveMultiStrike))
{
int attackType = Int(IntAttackType);
int mastery = Int(IntWeaponType);
bool cleaving = (attackType == 4 && mastery == 11) || (attackType == 1 && mastery != 11 && mastery != 0);
if (cleaving) d.Add(Cbt, "Cleaving");
else if (attackType is 160 or 166) d.Add(Cbt, "Multi-Strike");
else if (attackType == 486) d.Add(Cbt, "Multi-Strike (3)");
}
// ── Slayer ──────────────────────────────────────────────────────────────
if (Has(Field.Slayer) && Show(MagItemInfoField.Slayer))
{
string? slayer = MagItemInfoTables.CreatureTypeName(Int(IntSlayerCreature));
if (slayer != null) d.Add(Cbt, slayer + " Slayer");
}
// ── Tinks + applied materials (TinkerLog) ──────────────────────────────
int tinks = Int(IntTinks);
if (tinks > 0 && Show(MagItemInfoField.Tinks)) d.Add(Id, "Tinks " + I(tinks));
if (Show(MagItemInfoField.Applied))
{
string applied = FormatTinkerLog(item.GetString(StringTinkerLog));
if (applied.Length > 0) d.Add(Id, "Applied: " + applied);
}
// ── Damage ──────────────────────────────────────────────────────────────
// T11 weapon grade sits with the identity fields: "Grade S (100%)".
if (Has(Field.Damage) && Show(MagItemInfoField.Damage) && t11.GradeRank > 0)
d.Add(Id, t11.DamagePercent >= 0 ? $"Grade {t11.Grade} ({I(t11.DamagePercent)}%)" : $"Grade {t11.Grade}");
if (Has(Field.Damage) && Show(MagItemInfoField.Damage))
AddDamage(d, cls, Int(IntMaxDamage), Dbl(FloatVariance, 0), Int(IntElementalBonus),
Dbl(FloatDamageMod, 1), Dbl(FloatVsMonsters, 1));
// ── Attack / defense / mana conversion percents ───────────────────────
bool defenses = Show(MagItemInfoField.Defenses);
if (Has(Field.AttackBonus) && Show(MagItemInfoField.Attack)) AddPercent(d, Dbl(FloatAttack, 1), "%a", 0);
if (Has(Field.MeleeDefense) && defenses) AddPercent(d, Dbl(FloatMeleeDefense, 1), "%md", 0);
if (Has(Field.MagicDefense) && defenses) AddPercent(d, Dbl(FloatMagicDefense, 1), "%mgc.d", 1);
if (Has(Field.MissileDefense) && defenses) AddPercent(d, Dbl(FloatMissileDefense, 1), "%msl.d", 1);
if (Has(Field.ManaConversion) && Show(MagItemInfoField.ManaConversion))
{
double mc = Dbl(FloatManaConversion, 0);
if (mc != 0) d.Add(Cbt, Math.Round(mc * 100).ToString(CultureInfo.InvariantCulture) + "%mc");
}
// ── Spells ──────────────────────────────────────────────────────────────
bool unenchantable = Int(IntResistMagic) >= 9999;
if (Show(MagItemInfoField.Spells))
AddSpells(d, item.SpellIds, unenchantable, options.AllSpells, options.MaxListedSpells);
// ── Requirements ────────────────────────────────────────────────────────
if (Show(MagItemInfoField.Wield))
{
AddWieldRequirement(d, Int(IntWieldReq), Int(IntWieldSkill), Int(IntWieldValue));
AddWieldRequirement(d, Int(IntWieldReq2), Int(IntWieldSkill2), Int(IntWieldValue2));
// T11 gates (item augs, Triune Weave, charms) only exist as "Wield requires:" text.
foreach (T11WieldGate gate in t11.WieldGates)
d.Add(Req, $"Wield {gate.Amount.ToString("N0", CultureInfo.InvariantCulture)} {GateName(gate.Counter)}");
}
if (Show(MagItemInfoField.Activation))
{
int useLevel = Int(IntUseRequiresLevel);
if (useLevel > 0) d.Add(Req, "Lvl " + I(useLevel));
// "Melee Defense 300 to Activate" — hidden when the wield requirement already covers it.
int actSkill = Int(IntActivationSkill), actLevel = Int(IntActivationLevel);
if (actLevel > 0 && (Int(IntWieldSkill) != actSkill || Int(IntWieldValue) < actLevel))
d.Add(Req, $"{SkillName(actSkill)} {I(actLevel)} to Activate");
// Summoning essences / gems.
int useSkill = Int(IntUseRequiresSkill), useSkillLvl = Int(IntUseRequiresSkillLvl), useSpec = Int(IntUseRequiresSpec);
if (useSkill > 0 && useSkillLvl > 0) d.Add(Req, $"{SkillName(useSkill)} {I(useSkillLvl)}");
if (useSpec > 0 && useSkillLvl > 0) d.Add(Req, $"Spec {SkillName(useSpec)} {I(useSkillLvl)}");
}
int diff = Int(IntItemDifficulty);
if (diff > 0 && Show(MagItemInfoField.Difficulty)) d.Add(Req, "Diff " + I(diff));
// ── Workmanship ─────────────────────────────────────────────────────────
int work = Show(MagItemInfoField.Craft) ? Int(IntWorkmanship) : 0;
if (cls == AcObjectClass.Salvage)
{
int items = Int(IntNumItemsInMaterial);
if (work > 0)
{
double avg = items > 0 ? (double)work / items : work;
d.Add(Id, "Work " + avg.ToString("N2", CultureInfo.InvariantCulture));
}
}
else if (work > 0 && tinks != 10) // Mag: hide craft once fully tinked
{
d.Add(Id, "Craft " + I(work));
}
// ── Unenchantable armor: base protections [S/P/B/C/F/A/L] ─────────────
if (cls == AcObjectClass.Armor && unenchantable && Show(MagItemInfoField.Protections))
{
var prot = new StringBuilder("[");
for (uint i = 0; i < 7; i++)
{
if (i > 0) prot.Append('/');
prot.Append(Dbl(FloatArmorVsSlash + i, 0).ToString("N1", CultureInfo.InvariantCulture));
}
d.Add(Cbt, prot.Append(']').ToString());
}
if (options.ShowValueAndBurden)
{
int value = Int(IntValue);
if (value > 0) d.Add(Req, "Value " + value.ToString("N0", CultureInfo.InvariantCulture));
int burden = Int(IntBurden);
if (burden > 0) d.Add(Req, "BU " + I(burden));
}
// ── Ratings ─────────────────────────────────────────────────────────────
if (Show(MagItemInfoField.Ratings))
{
d.Add(MagItemSection.Ratings, RatingsCluster(item, options.HiddenRatings));
// T11 zone modifiers: the server drops a modifier's Gear* rating from the ratings it
// sends, so the modifier lines are the only place those values appear.
if (t11.Modifiers.Count > 0)
{
var mods = new List<string>(t11.Modifiers.Count);
foreach (T11Modifier m in t11.Modifiers)
{
string mod = m.Value != 0 ? $"{m.Name} {(m.Value > 0 ? "+" : "")}{I(m.Value)}" : m.Name;
if (m.Tinkered != 0) mod += $" ({(m.Tinkered > 0 ? "+" : "")}{I(m.Tinkered)} tink)";
if (m.Locked) mod += " (Locked)";
mods.Add(mod);
}
d.Add(MagItemSection.Ratings, "Mods: " + string.Join(", ", mods));
}
}
if (cls == AcObjectClass.Misc && Show(MagItemInfoField.Keyring)
&& item.Name.Contains("Keyring", StringComparison.OrdinalIgnoreCase))
{
d.Add(Id, "Keys: " + I(Int(IntNumKeys)));
d.Add(Id, "Uses: " + I(Int(IntStructure)));
}
return d;
}
/// <summary>Mag imbue labels ("CS AR"), plus the ACE flags Mag predates (missile imbue, nether
/// rend); empty when no known bit is set.</summary>
private static string ImbueLabels(int mask, IReadOnlyDictionary<int, string> strengths)
{
if (mask == 0) return string.Empty;
var sb = new StringBuilder();
// Bare labels stay Mag-style "CS AR"; once a strength is shown, commas keep values readable.
string sep = strengths.Count > 0 ? ", " : " ";
void Flag(int bit, string label)
{
if ((mask & bit) == 0) return;
if (sb.Length > 0) sb.Append(sep);
sb.Append(label);
if (strengths.TryGetValue(bit, out string? value)) sb.Append(' ').Append(value);
}
Flag(0x0001, "CS");
Flag(0x0002, "CB");
Flag(0x0004, "AR");
Flag(0x0008, "SlashRend");
Flag(0x0010, "PierceRend");
Flag(0x0020, "BludgeRend");
Flag(0x0040, "AcidRend");
Flag(0x0080, "FrostRend");
Flag(0x0100, "LightRend");
Flag(0x0200, "FireRend");
Flag(0x4000, "NetherRend");
Flag(0x0400, "MeleeImbue");
Flag(0x0800, "MissileImbue");
Flag(0x1000, "MagicImbue");
Flag(0x2000, "Hematited");
Flag(0x20000000, "MagicAbsorb");
return sb.ToString(); // only unknown bits → empty → field skipped
}
// ACECustom "Property Details:" imbue lines, e.g. "- Fire Rending: +176% Dmg",
// "- Armor Rending: 12.5% Ignored", "- Crippling Blow: 2.5x Crit Dmg". The value may carry a
// culture space before '%' and group separators.
private static readonly Regex ImbueDetailLine = new(
@"^\s*-\s*(?<name>[A-Za-z' ]+?)\s*:\s*(?<value>[+-]?[\d.,]+\s?[%x])",
RegexOptions.Multiline | RegexOptions.CultureInvariant);
/// <summary>
/// Imbue bit → strength text ("+176%", "12.5%", "2.5x") from the description. Rendings are
/// matched by damage keyword because the server builds their names from DamageType.DisplayName.
/// </summary>
private static IReadOnlyDictionary<int, string> ImbueStrengths(string longDesc)
{
var result = new Dictionary<int, string>();
if (string.IsNullOrEmpty(longDesc)) return result;
foreach (Match m in ImbueDetailLine.Matches(longDesc))
{
int bit = ImbueBitForDetail(m.Groups["name"].Value);
if (bit != 0 && !result.ContainsKey(bit))
result[bit] = m.Groups["value"].Value.Replace(" ", "");
}
return result;
}
private static int ImbueBitForDetail(string name)
{
bool Has(string s) => name.Contains(s, StringComparison.OrdinalIgnoreCase);
if (Has("Critical Strike")) return 0x0001;
if (Has("Crippling Blow")) return 0x0002;
if (Has("Armor Rending")) return 0x0004;
if (!Has("Rending")) return 0;
if (Has("Slash")) return 0x0008;
if (Has("Pierc")) return 0x0010;
if (Has("Bludg")) return 0x0020;
if (Has("Acid")) return 0x0040;
if (Has("Cold") || Has("Frost")) return 0x0080;
if (Has("Electric") || Has("Lightning")) return 0x0100;
if (Has("Fire")) return 0x0200;
if (Has("Nether")) return 0x4000;
return 0;
}
/// <summary>Short wield-gate counter names: "Item Augs", "Triune Weave", charm names.</summary>
private static string GateName(T11Counter counter) =>
counter == T11Counter.ItemAugmentations ? "Item Augs" : T11Catalog.CounterName(counter);
/// <summary>Melee "min-max", variance, "+elem", "+mod%", wand "+N% vs. Monsters" (combat line).</summary>
private static void AddDamage(MagItemDescription d, AcObjectClass cls, int maxDmg, double variance,
int elemBonus, double dmgMod, double vsMonsters)
{
const MagItemSection Cbt = MagItemSection.Combat;
if (cls != AcObjectClass.MissileWeapon && maxDmg > 0)
{
string max = maxDmg.ToString(CultureInfo.InvariantCulture);
// The appraisal panel rounds the low end to a whole number (2069 * 0.865 → 1790).
long min = (long)Math.Round(maxDmg * (1 - variance), MidpointRounding.AwayFromZero);
d.Add(Cbt, variance > 0 ? min.ToString(CultureInfo.InvariantCulture) + "-" + max : max);
}
// Three places: loot variances are often x.xx5 and two places would misreport them.
if (variance > 0)
d.Add(Cbt, Math.Round(variance, 3).ToString("0.###", CultureInfo.InvariantCulture) + "v");
if (elemBonus != 0)
d.Add(Cbt, "+" + elemBonus.ToString(CultureInfo.InvariantCulture));
// A missing/zero multiplier means "no bonus" (0 would print as -100%).
if (dmgMod > 0 && dmgMod != 1)
d.Add(Cbt, "+" + Math.Round((dmgMod - 1) * 100).ToString(CultureInfo.InvariantCulture) + "%");
if (vsMonsters > 0 && vsMonsters != 1)
d.Add(Cbt, "+" + Math.Round((vsMonsters - 1) * 100).ToString(CultureInfo.InvariantCulture) + "% vs. Monsters");
}
/// <summary>Mag "+18%a" from a 1.0-based multiplier; skips missing (≤0) and neutral 1.0.</summary>
private static void AddPercent(MagItemDescription d, double multiplier, string suffix, int decimals)
{
if (multiplier <= 0 || multiplier == 1) return;
double pct = Math.Round((multiplier - 1) * 100, decimals);
if (pct == 0) return; // rounds to nothing at this precision
// Signed like the appraisal panel ("Bonus to Attack Skill +20%"); penalties keep their '-'.
d.Add(MagItemSection.Combat, (pct > 0 ? "+" : "") + pct.ToString(CultureInfo.InvariantCulture) + suffix);
}
/// <summary>"Wield Lvl 180" for a level requirement, else "Heavy Weapons 375".</summary>
private static void AddWieldRequirement(MagItemDescription d, int reqType, int skillOrAttr, int value)
{
// Int64 gates name a counter, not a skill; the T11 text supplies those.
if (value <= 0 || reqType == WieldReqInt64Stat) return;
string v = value.ToString(CultureInfo.InvariantCulture);
d.Add(MagItemSection.Requirements, reqType == 7 // WieldRequirement.Level
? "Wield Lvl " + v
: SkillName(skillOrAttr) + " " + v);
}
private static string SkillName(int skill) =>
MagItemInfoTables.Skills.TryGetValue(skill, out string? name) ? name : $"Skill {skill}";
/// <summary>
/// Mag-Tools spell filter (ub-IT applies it to every item): keep cantrip Impen, Augmented
/// (trinket) spells, banes/Impen only on unenchantable gear, level 7+ weapon auras, and
/// named high-tier spells (cantrips); drop I–VI, level-7 lore buffs and Incantations.
/// Verbose lists every spell (capped) for troubleshooting.
/// </summary>
private static void AddSpells(MagItemDescription d, IReadOnlyList<int> spellIds, bool unenchantable,
bool verbose, int maxVerbose)
{
if (spellIds.Count == 0) return;
var ids = new List<int>(spellIds);
ids.Sort();
ids.Reverse(); // Mag lists highest spell id first
var seen = new HashSet<int>();
var verboseList = verbose ? new StringBuilder() : null;
int shown = 0, skippedVerbose = 0;
foreach (int id in ids)
{
if (!seen.Add(id)) continue;
bool known = SpellDatabase.HasSpell(id);
if (verboseList != null)
{
// Verbose is the troubleshooting view: list ids SpellData.txt doesn't know too.
if (shown >= maxVerbose) { skippedVerbose++; continue; }
verboseList.Append(shown == 0 ? "Spells: " : "; ")
.Append(known ? SpellDatabase.GetSpellName(id) : $"Spell {id}");
shown++;
continue;
}
if (!known) continue;
string name = SpellDatabase.GetSpellName(id);
SpellDatabase.TryGetSpellMeta(id, out int family, out int difficulty);
if (ShouldShowSpell(name, family, difficulty, unenchantable))
d.Add(MagItemSection.Spells, name);
}
if (verboseList == null || verboseList.Length == 0) return;
if (skippedVerbose > 0) verboseList.Append("; (+").Append(skippedVerbose).Append(" more spells)");
d.Add(MagItemSection.Spells, verboseList.ToString());
}
private static bool ShouldShowSpell(string name, int family, int difficulty, bool unenchantable)
{
if (name.Contains("Minor Impenetrability") || name.Contains("Major Impenetrability")
|| name.Contains("Epic Impenetrability") || name.Contains("Legendary Impenetrability"))
return true;
if (name.Contains("Augmented"))
return true;
// Banes / Impen / Brogard's: only meaningful on unenchantable gear (loot armor
// already reflects them in AL and protections).
bool baneLike = name.Contains(" Bane") || name.Contains("Impen") || name.StartsWith("Brogard", StringComparison.Ordinal);
if (baneLike) return unenchantable;
// Weapon auras (Elysa's Sight .. Swift Killer, Hermetic Link, Vision of the Hunter):
// level 7 (300) and 8+ (400+) only.
if ((family >= 152 && family <= 158) || family == 195 || family == 325)
return difficulty == 300 || difficulty >= 400;
if (name.EndsWith(" I") || name.EndsWith(" II") || name.EndsWith(" III")
|| name.EndsWith(" IV") || name.EndsWith(" V") || name.EndsWith(" VI"))
return false;
if (difficulty == 300) return false; // level-7 lore buffs (Might of the Lugians …)
if (name.Contains("Incantation")) return false;
return true; // cantrips: Legendary Strength, Epic Defender …
}
/// <summary>Rating cluster "[D 11, C 8, CD 4]" from ACE Gear* ratings 370–389
/// (<see cref="MagItemInfoCatalog.Ratings"/>); bit i of <paramref name="hiddenMask"/> skips rating i.</summary>
private static string RatingsCluster(IItemPropertySource item, int hiddenMask)
{
var sb = new StringBuilder();
var ratings = MagItemInfoCatalog.Ratings;
for (int i = 0; i < ratings.Length; i++)
{
if ((hiddenMask & (1 << i)) != 0) continue;
if (!item.TryGetInt(ratings[i].StatId, out int v) || v <= 0 || v > MaxPlausibleRating) continue;
sb.Append(sb.Length == 0 ? "[" : ", ").Append(ratings[i].Tag).Append(' ')
.Append(v.ToString(CultureInfo.InvariantCulture));
}
return sb.Length > 0 ? sb.Append(']').ToString() : string.Empty;
}
/// <summary>ACECustom TinkerLog CSV ("64,64,46") → "Steel x2, White Quartz".</summary>
private static string FormatTinkerLog(string csv)
{
if (string.IsNullOrWhiteSpace(csv)) return string.Empty;
var order = new List<int>();
var counts = new Dictionary<int, int>();
foreach (string raw in csv.Split(','))
{
if (!int.TryParse(raw.Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out int id) || id <= 0)
continue;
if (counts.TryGetValue(id, out int c)) counts[id] = c + 1;
else { counts[id] = 1; order.Add(id); }
}
var sb = new StringBuilder();
foreach (int id in order)
{
if (sb.Length > 0) sb.Append(", ");
sb.Append(MagItemInfoTables.Materials.TryGetValue(id, out string? name) ? name : $"material {id}");
if (counts[id] > 1) sb.Append(" x").Append(counts[id]);
}
return sb.ToString();
}
/// <summary>Max ballistic range (45° arc, v²/g) in yards; 0 when velocity is missing.</summary>
private static int MissileRangeYards(double velocity)
{
if (double.IsNaN(velocity) || velocity <= 0) return 0;
double meters = velocity * velocity / 9.8;
return (int)Math.Round(meters * 1.0936133);
}
private static string Fmt(double v) => Math.Round(v, 2).ToString(CultureInfo.InvariantCulture);
}
/// <summary><see cref="IItemPropertySource"/> over the live client object (RynthCore host reads).</summary>
internal sealed class CacheItemPropertySource : IItemPropertySource
{
private readonly RynthCore.PluginSdk.RynthCoreHost _host;
private readonly uint _id;
private IReadOnlyList<int>? _spells;
public CacheItemPropertySource(RynthCore.PluginSdk.RynthCoreHost host, WorldObject wo)
{
_host = host;
_id = unchecked((uint)wo.Id);
Name = wo.Name;
ObjectClass = wo.ObjectClass;
}
public string Name { get; }
public AcObjectClass ObjectClass { get; }
public bool TryGetInt(uint stype, out int value)
{
value = 0;
return _host.HasGetObjectIntProperty && _host.TryGetObjectIntProperty(_id, stype, out value);
}
public bool TryGetDouble(uint stype, out double value)
{
value = 0;
return _host.HasGetObjectDoubleProperty && _host.TryGetObjectDoubleProperty(_id, stype, out value);
}
public string GetString(uint stype) =>
_host.HasGetObjectStringProperty && _host.TryGetObjectStringProperty(_id, stype, out string? v) && v != null
? v
: string.Empty;
public IReadOnlyList<int> SpellIds => _spells ??= ReadSpells();
private IReadOnlyList<int> ReadSpells()
{
if (!_host.HasGetObjectSpellIds) return Array.Empty<int>();
uint[] buf = new uint[128];
int n = _host.GetObjectSpellIds(_id, buf, buf.Length);
if (n <= 0) return Array.Empty<int>();
int take = Math.Min(n, buf.Length);
var list = new List<int>(take);
for (int i = 0; i < take; i++) list.Add(unchecked((int)buf[i]));
return list;
}
}

View file

@ -0,0 +1,257 @@
// MagItemInfoSettings.cs — user options for the Mag-style item info line (/ra iteminfo).
//
// Stored per character inside LegacyUiSettings.ItemInfoSettings. Field visibility is kept as a
// *hidden* bitmask so any field added in a later release shows by default for existing profiles.
using System;
namespace RynthCore.Plugin.RynthAi.ItemInfo;
/// <summary>Toggleable sections of the item info line (bit set in HiddenFields = not printed).</summary>
[Flags]
public enum MagItemInfoField
{
None = 0,
Material = 1 << 0,
TypeMastery = 1 << 1,
Set = 1 << 2,
ArmorLevel = 1 << 3,
Imbues = 1 << 4,
ArmorCleave = 1 << 5,
CritStats = 1 << 6,
Splits = 1 << 7,
Range = 1 << 8,
CleaveMultiStrike = 1 << 9,
Slayer = 1 << 10,
Tinks = 1 << 11,
Applied = 1 << 12,
Damage = 1 << 13,
Attack = 1 << 14,
Defenses = 1 << 15,
ManaConversion = 1 << 16,
Spells = 1 << 17,
Wield = 1 << 18,
Activation = 1 << 19,
Difficulty = 1 << 20,
Craft = 1 << 21,
Protections = 1 << 22,
Ratings = 1 << 23,
Keyring = 1 << 24,
/// <summary>ACECustom T11 state: tier, weapon quality, Gear Grade, property slots, Tainted.</summary>
T11 = 1 << 25,
}
/// <summary>Persisted item-info options (JSON fields; see RynthAiJsonContext IncludeFields).</summary>
public sealed class MagItemInfoSettings
{
/// <summary>Spell list modes for <see cref="SpellMode"/>.</summary>
public const int SpellModeMag = 0, SpellModeAll = 1;
/// <summary>Mouse triggers for <see cref="ClickTrigger"/>.</summary>
public const int ClickOff = 0, ClickLeft = 1, ClickRight = 2;
/// <summary>Output layouts for <see cref="Layout"/>.</summary>
public const int LayoutOneLine = 0, LayoutPetLines = 1;
/// <summary><see cref="DetailChatType"/> value meaning "use <see cref="ChatType"/>".</summary>
public const int SameAsHeader = -1;
// ── When to print ────────────────────────────────────────────────────────
/// <summary>Print automatically when an item is selected.</summary>
public bool OnSelect;
/// <summary>
/// Print the selected item after a left (<see cref="ClickLeft"/>) or right (<see cref="ClickRight"/>)
/// click in the game world / inventory — also re-prints an item that was already selected.
/// </summary>
public int ClickTrigger = ClickOff;
/// <summary>On-select class filters (manual /ra iteminfo ignores them).</summary>
public bool OnSelectWeapons = true;
public bool OnSelectArmor = true;
public bool OnSelectJewelry = true;
public bool OnSelectOther = true;
/// <summary>Seconds to wait for an ID before printing partial data.</summary>
public float IdTimeoutSec = 3f;
// ── What to print ────────────────────────────────────────────────────────
/// <summary><see cref="MagItemInfoField"/> bits that are NOT printed.</summary>
public int HiddenFields;
/// <summary>Bit i set = <see cref="MagItemInfoCatalog.Ratings"/>[i] not printed.</summary>
public int HiddenRatings;
/// <summary>Append ", Value N, BU N".</summary>
public bool ShowValueAndBurden;
/// <summary><see cref="SpellModeMag"/> (Mag filter) or <see cref="SpellModeAll"/>.</summary>
public int SpellMode = SpellModeMag;
/// <summary>Cap for the "all spells" list.</summary>
public int MaxListedSpells = 26;
// ── How to print ─────────────────────────────────────────────────────────
/// <summary><see cref="LayoutPetLines"/> (pet-roster style lines) or <see cref="LayoutOneLine"/> (Mag one-liner).</summary>
public int Layout = LayoutPetLines;
/// <summary>AC chat type passed to WriteToChat (selects the chat colour / window).</summary>
public int ChatType = 1;
/// <summary>Chat type for pet-style lines 2+, or <see cref="SameAsHeader"/>.</summary>
public int DetailChatType = SameAsHeader;
/// <summary>
/// Text put in front of every line. RynthChat files lines starting "[RynthAi Item] " under
/// its Items tab (ChatClassifier.IsItemInfo).
/// </summary>
public string Prefix = "[RynthAi Item] ";
/// <summary>Item Info settings window open.</summary>
public bool ShowWindow;
public bool IsHidden(MagItemInfoField f) => (HiddenFields & (int)f) != 0;
public void SetHidden(MagItemInfoField f, bool hidden) =>
HiddenFields = hidden ? HiddenFields | (int)f : HiddenFields & ~(int)f;
public bool IsRatingHidden(int index) => (HiddenRatings & (1 << index)) != 0;
public void SetRatingHidden(int index, bool hidden) =>
HiddenRatings = hidden ? HiddenRatings | (1 << index) : HiddenRatings & ~(1 << index);
/// <summary>Clamp values a hand-edited or older profile could carry out of range.</summary>
public void Sanitize()
{
if (float.IsNaN(IdTimeoutSec) || IdTimeoutSec < 0.5f) IdTimeoutSec = 0.5f;
if (IdTimeoutSec > 15f) IdTimeoutSec = 15f;
if (SpellMode is not (SpellModeMag or SpellModeAll)) SpellMode = SpellModeMag;
MaxListedSpells = Math.Clamp(MaxListedSpells, 1, 64);
if (ChatType < 0 || ChatType > 31) ChatType = 1;
if (DetailChatType < SameAsHeader || DetailChatType > 31) DetailChatType = SameAsHeader;
if (ClickTrigger is not (ClickOff or ClickLeft or ClickRight)) ClickTrigger = ClickOff;
if (Layout is not (LayoutOneLine or LayoutPetLines)) Layout = LayoutPetLines;
Prefix ??= string.Empty;
if (Prefix.Length > 32) Prefix = Prefix[..32];
}
/// <summary>Back to first-run defaults (window stays open).</summary>
public void ResetToDefaults()
{
var d = new MagItemInfoSettings();
OnSelect = d.OnSelect;
ClickTrigger = d.ClickTrigger;
Layout = d.Layout;
DetailChatType = d.DetailChatType;
OnSelectWeapons = d.OnSelectWeapons; OnSelectArmor = d.OnSelectArmor;
OnSelectJewelry = d.OnSelectJewelry; OnSelectOther = d.OnSelectOther;
IdTimeoutSec = d.IdTimeoutSec;
HiddenFields = d.HiddenFields; HiddenRatings = d.HiddenRatings;
ShowValueAndBurden = d.ShowValueAndBurden;
SpellMode = d.SpellMode; MaxListedSpells = d.MaxListedSpells;
ChatType = d.ChatType; Prefix = d.Prefix;
}
}
/// <summary>Labels for the settings window and the /ra iteminfo field|rating commands.</summary>
public static class MagItemInfoCatalog
{
public readonly record struct FieldInfo(MagItemInfoField Field, string Label, string Example);
public readonly record struct RatingInfo(uint StatId, string Tag, string Name);
/// <summary>In print order.</summary>
public static readonly FieldInfo[] Fields =
{
new(MagItemInfoField.Material, "Material", "Gold Ornate Long Sword"),
new(MagItemInfoField.TypeMastery, "Damage type / mastery","(Slash Sword)"),
new(MagItemInfoField.Set, "Equipment set", "Noble Relic Set"),
new(MagItemInfoField.T11, "T11 tier / grade / slots", "T16, Gear B+ (4 lines), Props 3/5, Tainted"),
new(MagItemInfoField.ArmorLevel, "Armor level", "AL 650"),
new(MagItemInfoField.Imbues, "Imbues", "CS, AR, FireRend"),
new(MagItemInfoField.ArmorCleave, "Armor cleaving", "AC"),
new(MagItemInfoField.CritStats, "Crit mult / freq", "CritMult (1.5), CritFreq (0.15)"),
new(MagItemInfoField.Splits, "Split arrows", "Splits (2)"),
new(MagItemInfoField.Range, "Missile range", "Range 120yd"),
new(MagItemInfoField.CleaveMultiStrike, "Cleaving / Multi-Strike", "Cleaving"),
new(MagItemInfoField.Slayer, "Slayer", "Undead Slayer"),
new(MagItemInfoField.Tinks, "Tinks", "Tinks 4"),
new(MagItemInfoField.Applied, "Applied materials", "Applied: Steel x2"),
new(MagItemInfoField.Damage, "Damage", "152.48-236, 0.35v, +18, +10%"),
new(MagItemInfoField.Attack, "Attack bonus", "+18%a"),
new(MagItemInfoField.Defenses, "Defense bonuses", "12%md, 1.5%mgc.d, 1%msl.d"),
new(MagItemInfoField.ManaConversion, "Mana conversion", "6%mc"),
new(MagItemInfoField.Spells, "Spells", "Legendary Blood Thirst"),
new(MagItemInfoField.Wield, "Wield requirements", "Wield Lvl 180, Heavy Weapons 375"),
new(MagItemInfoField.Activation, "Activation / use reqs","Lvl 50, Melee Defense 300 to Activate"),
new(MagItemInfoField.Difficulty, "Arcane difficulty", "Diff 270"),
new(MagItemInfoField.Craft, "Craft / salvage work", "Craft 8"),
new(MagItemInfoField.Protections, "Protections (unenchantable armor)", "[1.0/0.8/1.2/...]"),
new(MagItemInfoField.Ratings, "Ratings", "[D 3, CD 2]"),
new(MagItemInfoField.Keyring, "Keyring keys / uses", "Keys: 3, Uses: 25"),
};
/// <summary>ACE gear ratings (PropertyInt 370–389) in Mag print order.</summary>
public static readonly RatingInfo[] Ratings =
{
new(370, "D", "Damage"),
new(371, "DR", "Damage Resist"),
new(372, "C", "Crit"),
new(374, "CD", "Crit Damage"),
new(373, "CR", "Crit Resist"),
new(375, "CDR", "Crit Damage Resist"),
new(376, "HB", "Healing Boost"),
new(379, "V", "Vitality"),
new(377, "NR", "Nether Resist"),
new(378, "LR", "Life Resist"),
new(383, "PKD", "PK Damage"),
new(384, "PKDR", "PK Damage Resist"),
new(388, "OP", "Overpower"),
new(389, "OPR", "Overpower Resist"),
};
/// <summary>Labels for <see cref="MagItemInfoSettings.ClickTrigger"/>, indexed by value.</summary>
public static readonly string[] ClickTriggers = { "Off", "Left mouse click", "Right mouse click" };
/// <summary>Labels for <see cref="MagItemInfoSettings.Layout"/>, indexed by value.</summary>
public static readonly string[] Layouts = { "One line (Mag-Tools)", "Pet-style lines" };
/// <summary>Common AC chat types for the colour picker (value passed to WriteToChat).</summary>
public static readonly (int Type, string Label)[] ChatTypes =
{
(0, "0 - Broadcast"),
(1, "1 - RynthAi default"),
(2, "2 - Speech"),
(3, "3 - Tell"),
(4, "4 - Outgoing tell"),
(5, "5 - System"),
(6, "6 - Combat"),
(7, "7 - Magic"),
(8, "8 - Channels"),
(10, "10 - Social"),
(12, "12 - Emote"),
(13, "13 - Advancement"),
(15, "15 - Help"),
(16, "16 - Appraisal"),
(17, "17 - Spellcasting"),
(18, "18 - Allegiance"),
(19, "19 - Fellowship"),
(21, "21 - Combat (enemy)"),
(22, "22 - Combat (self)"),
(24, "24 - Craft"),
(25, "25 - Salvaging"),
};
/// <summary>Field by enum name or label word, case-insensitive ("ratings", "slayer", "typemastery").</summary>
public static bool TryFindField(string key, out MagItemInfoField field)
{
foreach (var f in Fields)
{
if (f.Field.ToString().Equals(key, StringComparison.OrdinalIgnoreCase)
|| f.Label.Replace(" ", string.Empty).StartsWith(key, StringComparison.OrdinalIgnoreCase))
{
field = f.Field;
return true;
}
}
field = MagItemInfoField.None;
return false;
}
/// <summary>Rating index by tag ("CD") or name ("critdamage"), case-insensitive.</summary>
public static int FindRating(string key)
{
for (int i = 0; i < Ratings.Length; i++)
{
if (Ratings[i].Tag.Equals(key, StringComparison.OrdinalIgnoreCase)
|| Ratings[i].Name.Replace(" ", string.Empty).Equals(key, StringComparison.OrdinalIgnoreCase))
return i;
}
return -1;
}
}

View file

@ -0,0 +1,159 @@
// MagItemInfoTables.cs — name tables for the Mag-style item info line (MagItemDescriber).
// Skill / mastery / set / material names follow UtilityBelt ub-IT (Lib/ItemInfoHelper/Dictionaries.cs,
// itself from Mag-Tools / Alinco / VTank). Slayer names use the full ACE CreatureType enum instead of
// ub-IT's 17-entry subset so every slayer resolves.
using System.Collections.Generic;
using System.Text;
namespace RynthCore.Plugin.RynthAi.ItemInfo;
internal static class MagItemInfoTables
{
/// <summary>Skill id → name (wield / activation / summoning requirements).</summary>
public static readonly Dictionary<int, string> Skills = new()
{
{ 0x01, "Axe" }, { 0x02, "Bow" }, { 0x03, "Crossbow" }, { 0x04, "Dagger" }, { 0x05, "Mace" },
{ 0x06, "Melee Defense" }, { 0x07, "Missile Defense" }, { 0x08, "Sling" }, { 0x09, "Spear" },
{ 0x0A, "Staff" }, { 0x0B, "Sword" }, { 0x0C, "Thrown Weapons" }, { 0x0D, "Unarmed Combat" },
{ 0x0E, "Arcane Lore" }, { 0x0F, "Magic Defense" }, { 0x10, "Mana Conversion" },
{ 0x12, "Item Tinkering" }, { 0x13, "Assess Person" }, { 0x14, "Deception" }, { 0x15, "Healing" },
{ 0x16, "Jump" }, { 0x17, "Lockpick" }, { 0x18, "Run" }, { 0x1B, "Assess Creature" },
{ 0x1C, "Weapon Tinkering" }, { 0x1D, "Armor Tinkering" }, { 0x1E, "Magic Item Tinkering" },
{ 0x1F, "Creature Enchantment" }, { 0x20, "Item Enchantment" }, { 0x21, "Life Magic" },
{ 0x22, "War Magic" }, { 0x23, "Leadership" }, { 0x24, "Loyalty" }, { 0x25, "Fletching" },
{ 0x26, "Alchemy" }, { 0x27, "Cooking" }, { 0x28, "Salvaging" }, { 0x29, "Two Handed Combat" },
{ 0x2A, "Gearcraft" }, { 0x2B, "Void" }, { 0x2C, "Heavy Weapons" }, { 0x2D, "Light Weapons" },
{ 0x2E, "Finesse Weapons" }, { 0x2F, "Missile Weapons" }, { 0x30, "Shield" }, { 0x31, "Dual Wield" },
{ 0x32, "Recklessness" }, { 0x33, "Sneak Attack" }, { 0x34, "Dirty Fighting" }, { 0x35, "Challenge" },
{ 0x36, "Summoning" },
};
/// <summary>ACE PropertyInt.WeaponType (353) → mastery name.</summary>
public static readonly Dictionary<int, string> Masteries = new()
{
{ 1, "Unarmed Weapon" }, { 2, "Sword" }, { 3, "Axe" }, { 4, "Mace" }, { 5, "Spear" }, { 6, "Dagger" },
{ 7, "Staff" }, { 8, "Bow" }, { 9, "Crossbow" }, { 10, "Thrown" }, { 11, "Two Handed Combat" }, { 12, "Wand" },
};
/// <summary>ACE PropertyInt.MaterialType (131) → material name.</summary>
public static readonly Dictionary<int, string> Materials = new()
{
{ 1, "Ceramic" }, { 2, "Porcelain" }, { 4, "Linen" }, { 5, "Satin" }, { 6, "Silk" }, { 7, "Velvet" },
{ 8, "Wool" }, { 10, "Agate" }, { 11, "Amber" }, { 12, "Amethyst" }, { 13, "Aquamarine" },
{ 14, "Azurite" }, { 15, "Bag of Abyssal-Touched" }, { 16, "Black Opal" }, { 17, "Bloodstone" },
{ 18, "Carnelian" }, { 19, "Citrine" }, { 20, "Diamond" }, { 21, "Emerald" }, { 22, "Fire Opal" },
{ 23, "Green Garnet" }, { 24, "Green Jade" }, { 25, "Hematite" }, { 26, "Imperial Topaz" }, { 27, "Jet" },
{ 28, "Lapis Lazuli" }, { 29, "Lavender Jade" }, { 30, "Malachite" }, { 31, "Moonstone" }, { 32, "Onyx" },
{ 33, "Opal" }, { 34, "Peridot" }, { 35, "Red Garnet" }, { 36, "Red Jade" }, { 37, "Rose Quartz" },
{ 38, "Ruby" }, { 39, "Sapphire" }, { 40, "Smokey Quartz" }, { 41, "Sunstone" }, { 42, "Tiger Eye" },
{ 43, "Tourmaline" }, { 44, "Turquoise" }, { 45, "White Jade" }, { 46, "White Quartz" },
{ 47, "White Sapphire" }, { 48, "Yellow Garnet" }, { 49, "Yellow Topaz" }, { 50, "Zircon" },
{ 51, "Ivory" }, { 52, "Leather" }, { 53, "Armoredillo Hide" }, { 54, "Gromnie Hide" },
{ 55, "Reed Shark Hide" }, { 57, "Brass" }, { 58, "Bronze" }, { 59, "Copper" }, { 60, "Gold" },
{ 61, "Iron" }, { 62, "Pyreal" }, { 63, "Silver" }, { 64, "Steel" }, { 66, "Alabaster" },
{ 67, "Granite" }, { 68, "Marble" }, { 69, "Obsidian" }, { 70, "Sandstone" }, { 71, "Serpentine" },
{ 73, "Ebony" }, { 74, "Mahogany" }, { 75, "Oak" }, { 76, "Pine" }, { 77, "Teak" },
};
/// <summary>ACE PropertyInt.EquipmentSetId (265) → set name.</summary>
public static readonly Dictionary<int, string> EquipmentSets = BuildSets();
/// <summary>ACE CreatureType enum, index = value (0..101). Used for SlayerCreatureType (166).</summary>
private static readonly string[] CreatureTypes =
{
"Invalid", "Olthoi", "Banderling", "Drudge", "Mosswart", "Lugian", "Tumerok", "Mite", "Tusker",
"Phyntos Wasp", "Rat", "Auroch", "Cow", "Golem", "Undead", "Gromnie", "Reedshark", "Armoredillo",
"Fae", "Virindi", "Wisp", "Knathtead", "Shadow", "Mattekar", "Mumiyah", "Rabbit", "Sclavus",
"Shallows Shark", "Monouga", "Zefir", "Skeleton", "Human", "Shreth", "Chittick", "Moarsman",
"Olthoi Larvae", "Slithis", "Deru", "Fire Elemental", "Snowman", "Unknown", "Bunny",
"Lightning Elemental", "Rockslide", "Grievver", "Niffis", "Ursuin", "Crystal", "Hollow Minion",
"Scarecrow", "Idol", "Empyrean", "Hopeslayer", "Doll", "Marionette", "Carenzi", "Siraluun",
"Aun Tumerok", "Hea Tumerok", "Simulacrum", "Acid Elemental", "Frost Elemental", "Elemental",
"Statue", "Wall", "Altered Human", "Device", "Harbinger", "Dark Sarcophagus", "Chicken",
"Gotrok Lugian", "Margul", "Bleached Rabbit", "Nasty Rabbit", "Grimacing Rabbit", "Burun", "Target",
"Ghost", "Fiun", "Eater", "Penguin", "Ruschk", "Thrungus", "Viamontian Knight", "Remoran", "Swarm",
"Moar", "Enchanted Arms", "Sleech", "Mukkir", "Merwart", "Food", "Paradox Olthoi", "Harvest",
"Energy", "Apparition", "Aerbax", "Touched", "Blighted Moarsman", "Gear Knight", "Gurog", "A'nekshay",
};
/// <summary>Slayer creature name, or null for 0 / unknown values.</summary>
public static string? CreatureTypeName(int value) =>
value > 0 && value < CreatureTypes.Length ? CreatureTypes[value] : null;
/// <summary>
/// ACE DamageType flags (45) → "Slash", "Slash/Pierce", "Lightning" … Empty when no known bit is set.
/// </summary>
public static string DamageTypeName(int flags)
{
if (flags <= 0) return string.Empty;
var sb = new StringBuilder();
void Add(int bit, string name)
{
if ((flags & bit) == 0) return;
if (sb.Length > 0) sb.Append('/');
sb.Append(name);
}
Add(0x001, "Slash");
Add(0x002, "Pierce");
Add(0x004, "Bludgeon");
Add(0x008, "Cold");
Add(0x010, "Fire");
Add(0x020, "Acid");
Add(0x040, "Lightning");
Add(0x400, "Nether");
return sb.ToString();
}
private static Dictionary<int, string> BuildSets()
{
var d = new Dictionary<int, string>
{
{ 2, "Test" }, { 4, "Carraida's Benediction" }, { 5, "Noble Relic Set" }, { 6, "Ancient Relic Set" },
{ 7, "Relic Alduressa Set" }, { 8, "Shou-jen Set" }, { 9, "Empyrean Rings Set" },
{ 10, "Arm, Mind, Heart Set" }, { 11, "Coat of the Perfect Light Set" },
{ 12, "Leggings of Perfect Light Set" }, { 13, "Soldier's Set" }, { 14, "Adept's Set" },
{ 15, "Archer's Set" }, { 16, "Defender's Set" }, { 17, "Tinker's Set" }, { 18, "Crafter's Set" },
{ 19, "Hearty Set" }, { 20, "Dexterous Set" }, { 21, "Wise Set" }, { 22, "Swift Set" },
{ 23, "Hardened Set" }, { 24, "Reinforced Set" }, { 25, "Interlocking Set" },
{ 26, "Flame Proof Set" }, { 27, "Acid Proof Set" }, { 28, "Cold Proof Set" },
{ 29, "Lightning Proof Set" }, { 30, "Dedication Set" }, { 31, "Gladiatorial Clothing Set" },
{ 32, "Ceremonial Clothing" }, { 33, "Protective Clothing" }, { 34, "Noobie Armor" },
{ 35, "Sigil of Defense" }, { 36, "Sigil of Destruction" }, { 37, "Sigil of Fury" },
{ 38, "Sigil of Growth" }, { 39, "Sigil of Vigor" }, { 40, "Heroic Protector Set" },
{ 41, "Heroic Destroyer Set" }, { 42, "Olthoi Armor D Red" }, { 43, "Olthoi Armor C Rat" },
{ 44, "Olthoi Armor C Red" }, { 45, "Olthoi Armor D Rat" }, { 46, "Upgraded Relic Alduressa Set" },
{ 47, "Upgraded Ancient Relic Set" }, { 48, "Upgraded Noble Relic Set" },
{ 49, "Weave of Alchemy" }, { 50, "Weave of Arcane Lore" }, { 51, "Weave of Armor Tinkering" },
{ 52, "Weave of Assess Person" }, { 53, "Weave of Light Weapons" }, { 54, "Weave of Missile Weapons" },
{ 55, "Weave of Cooking" }, { 56, "Weave of Creature Enchantment" }, { 57, "Weave of Missile Weapons" },
{ 58, "Weave of Finesse" }, { 59, "Weave of Deception" }, { 60, "Weave of Fletching" },
{ 61, "Weave of Healing" }, { 62, "Weave of Item Enchantment" }, { 63, "Weave of Item Tinkering" },
{ 64, "Weave of Leadership" }, { 65, "Weave of Life Magic" }, { 66, "Weave of Loyalty" },
{ 67, "Weave of Light Weapons" }, { 68, "Weave of Magic Defense" },
{ 69, "Weave of Magic Item Tinkering" }, { 70, "Weave of Mana Conversion" },
{ 71, "Weave of Melee Defense" }, { 72, "Weave of Missile Defense" }, { 73, "Weave of Salvaging" },
{ 74, "Weave of Light Weapons" }, { 75, "Weave of Light Weapons" }, { 76, "Weave of Heavy Weapons" },
{ 77, "Weave of Missile Weapons" }, { 78, "Weave of Two Handed Combat" }, { 79, "Weave of Light Weapons" },
{ 80, "Weave of Void Magic" }, { 81, "Weave of War Magic" }, { 82, "Weave of Weapon Tinkering" },
{ 83, "Weave of Assess Creature" }, { 84, "Weave of Dirty Fighting" }, { 85, "Weave of Dual Wield" },
{ 86, "Weave of Recklessness" }, { 87, "Weave of Shield" }, { 88, "Weave of Sneak Attack" },
{ 89, "Ninja_New" }, { 90, "Weave of Summoning" }, { 91, "Shrouded Soul" }, { 92, "Darkened Mind" },
{ 93, "Clouded Spirit" }, { 130, "Shimmering Shadows" }, { 131, "Brown Society Locket" },
{ 132, "Yellow Society Locket" }, { 133, "Red Society Band" }, { 134, "Green Society Band" },
{ 135, "Purple Society Band" }, { 136, "Blue Society Band" }, { 137, "Gauntlet Garb" },
{ 138, "Paragon" }, { 139, "Paragon" }, { 140, "Paragon" },
};
// 94..129: Minor / Major / Blackfire × Stinging / Sparking / Smoldering / Shivering ×
// Shrouded Soul / Darkened Mind / Clouded Spirit (same order as the VTank set list).
string[] tiers = { "Minor", "Major", "Blackfire" };
string[] souls = { "Shrouded Soul", "Darkened Mind", "Clouded Spirit" };
string[] elements = { "Stinging", "Sparking", "Smoldering", "Shivering" };
int id = 94;
foreach (string tier in tiers)
foreach (string soul in souls)
foreach (string element in elements)
d[id++] = $"{tier} {element} {soul}";
return d;
}
}

View file

@ -89,11 +89,11 @@ internal sealed class Jumper
_turningStartedAt = DateTime.UtcNow;
if (_host.HasTurnToHeading)
_host.TurnToHeadingBy("Jump", _targetHeading);
_host.Log($"[Jumper] Start turn->{_targetHeading:F0} letters='{directionLetters}' hold={_msToHoldDown}ms");
RynthLog.Write(LogCat.Jumper, $"[Jumper] Start turn->{_targetHeading:F0} letters='{directionLetters}' hold={_msToHoldDown}ms");
}
else
{
_host.Log($"[Jumper] Start jump (no turn) letters='{directionLetters}' hold={_msToHoldDown}ms");
RynthLog.Write(LogCat.Jumper, $"[Jumper] Start jump (no turn) letters='{directionLetters}' hold={_msToHoldDown}ms");
}
return true;
}
@ -118,7 +118,7 @@ internal sealed class Jumper
{
_isTurning = false;
if (_host.TryGetPlayerHeading(out float current))
_host.Log($"[Jumper] Turn done heading={current:F1}");
RynthLog.Write(LogCat.Jumper, $"[Jumper] Turn done heading={current:F1}");
}
if (_needToJump && !_isTurning)
@ -141,12 +141,12 @@ internal sealed class Jumper
RestoreNav();
_waitingForJump = false;
_addW = _addX = _addZ = _addC = _addShift = false;
_host.Log("[Jumper] Settle complete -> idle");
RynthLog.Write(LogCat.Jumper, "[Jumper] Settle complete -> idle");
}
}
catch (Exception ex)
{
_host.Log($"[Jumper] Tick exception: {ex.GetType().Name}: {ex.Message}");
RynthLog.Write(LogCat.Jumper, $"[Jumper] Tick exception: {ex.GetType().Name}: {ex.Message}");
Cancel();
}
}
@ -166,7 +166,7 @@ internal sealed class Jumper
started = _host.CommenceJump();
_charging = started;
_chargeStartedAt = DateTime.UtcNow;
_host.Log($"[Jumper] CommenceJump ok={started} hold={_msToHoldDown}ms " +
RynthLog.Write(LogCat.Jumper, $"[Jumper] CommenceJump ok={started} hold={_msToHoldDown}ms " +
$"w={_addW} x={_addX} z={_addZ} c={_addC} shift={_addShift}");
}
else
@ -174,7 +174,7 @@ internal sealed class Jumper
started = _host.HasTapJump && _host.TapJump();
_waitingForJump = started;
_jumpStartedAt = DateTime.UtcNow;
_host.Log($"[Jumper] TapJump fallback ok={started} " +
RynthLog.Write(LogCat.Jumper, $"[Jumper] TapJump fallback ok={started} " +
$"w={_addW} x={_addX} z={_addZ} c={_addC} shift={_addShift}");
}
@ -200,13 +200,13 @@ internal sealed class Jumper
if (_host.HasLaunchJumpWithMotion)
{
released = _host.LaunchJumpWithMotion(_addShift, _addW, _addX, _addZ, _addC);
_host.Log($"[Jumper] LaunchJumpWithMotion ok={released} charged={_msToHoldDown}ms " +
RynthLog.Write(LogCat.Jumper, $"[Jumper] LaunchJumpWithMotion ok={released} charged={_msToHoldDown}ms " +
$"w={_addW} x={_addX} z={_addZ} c={_addC} shift={_addShift}");
}
else
{
released = _host.HasDoJump && _host.DoJump(true);
_host.Log($"[Jumper] DoJump fallback ok={released} charged={_msToHoldDown}ms");
RynthLog.Write(LogCat.Jumper, $"[Jumper] DoJump fallback ok={released} charged={_msToHoldDown}ms");
}
}

View file

@ -11,9 +11,16 @@ internal sealed class LegacyAdvancedSettingsUi
// Scratch buffer for the "never attack" name entry box.
private string _newBlacklistName = "";
// Server Features list being edited (committed on Enter / focus loss); null = show the saved list.
private string? _serverNamesEdit;
private static readonly string[] AttackHeights = { "Low", "Medium", "High" };
private static readonly string[] NavLabelModeNames = { "Off", "Numbers", "Numbers and names" };
private const string NavResumeNearestTip =
"On: starting the macro, loading a Circular or Linear route, and carrying on after a fight, loot, buff or door\n" +
"that moved you 10 yd or more all head for the closest waypoint on the route. A waypoint you have already\n" +
"walked past is skipped for the one after it, so nav doesn't turn back. Once routes only look ahead.\n" +
"Off: nav carries on to the waypoint it was heading for, and a loaded route starts at its first point.";
private static readonly string[] TargetSelectionNames = { "Lowest health", "Closest", "Farthest", "Least turning" };
private static readonly string[] LootOwnershipModes = { "My Kills Only", "Fellowship Kills", "All Corpses" };
@ -27,6 +34,15 @@ internal sealed class LegacyAdvancedSettingsUi
private Func<string>? _autoVendorStatus;
public void SetAutoVendorStatusProvider(Func<string> status) => _autoVendorStatus = status;
// Buffing page: the Force Buff button's actions and the list of buffs the unusable-buff
// filter is leaving out (wired by RynthAiPlugin once the BuffManager exists).
private Action? _forceBuff, _cancelBuff;
private Func<string>? _buffSkips;
public void SetBuffActions(Action? force, Action? cancel, Func<string>? skips)
{
_forceBuff = force; _cancelBuff = cancel; _buffSkips = skips;
}
private Func<string>? _autoTradeStatus;
public void SetAutoTradeStatusProvider(Func<string> status) => _autoTradeStatus = status;
private string _newAutoAcceptPattern = "";
@ -68,6 +84,35 @@ internal sealed class LegacyAdvancedSettingsUi
ImGui.End();
}
/// <summary>Settings > Misc "Server Features": the world list and the manual override (ServerFeatureGate).</summary>
private void RenderServerFeatures()
{
ImGui.Text("Server Features (ILT / infinite attributes)");
ImGui.TextDisabled(IltHub.ServerFeatureGate.Describe(_settings));
string text = _serverNamesEdit ?? IltHub.ServerFeatureGate.FormatList(_settings.FeatureServerNames);
ImGui.SetNextItemWidth(320);
bool enter = ImGui.InputTextWithHint("Servers##featureServers", "InfiniteLeaftide, *Leaftide*", ref text, 512,
ImGuiInputTextFlags.EnterReturnsTrue);
if (ImGui.IsItemActive() || enter) _serverNamesEdit = text;
if ((enter || ImGui.IsItemDeactivatedAfterEdit()) && _serverNamesEdit != null)
{
_settings.FeatureServerNames = IltHub.ServerFeatureGate.ParseList(_serverNamesEdit);
_serverNamesEdit = null;
}
else if (!ImGui.IsItemActive()) _serverNamesEdit = null;
if (ImGui.IsItemHovered())
ImGui.SetTooltip("Comma-separated world names that turn on the Mini Remote's ILT tabs, the Progression\n" +
"planners and the attribute raiser. * is a wildcard (*Leaftide* matches any\n" +
"name containing Leaftide). Case does not matter.");
ImGui.Checkbox("Force enable on this server (manual override)", ref _settings.ForceServerFeatures);
if (ImGui.IsItemHovered())
ImGui.SetTooltip("Turn the features on for whatever world you are on, even if it is not in the list.\n" +
"Each feature still follows what the server reports (for example /xp off keeps\n" +
"the attribute raiser off).");
}
private void RenderVendoring()
{
ImGui.Text("AutoVendor (UtilityBelt)");
@ -279,6 +324,10 @@ internal sealed class LegacyAdvancedSettingsUi
ImGui.SetTooltip("When acid or lava hurts you, stop everything (combat, buffs, healing, looting)\nand walk back out the way you came. The spot is remembered so the patrol avoids it.\nTurn off for a character that walks through acid on purpose.");
ImGui.Checkbox("Enable Raycasting", ref _settings.EnableRaycasting);
ImGui.Separator();
ImGui.Spacing();
RenderServerFeatures();
ImGui.Separator();
ImGui.Spacing();
ImGui.Text("Missile Arc Velocities (m/s)");
@ -507,6 +556,32 @@ internal sealed class LegacyAdvancedSettingsUi
"Lower = faster buff chains. 400ms is a good balance.\n" +
"Below 200ms may cause fizzles or dropped casts on laggy servers.");
ImGui.SetNextItemWidth(180);
ImGui.SliderInt("Stuck Cast Break (ms)", ref _settings.StuckCastBreakMs, 0, 20000);
if (ImGui.IsItemHovered())
ImGui.SetTooltip(
"The longest a cast may stay unanswered before it is broken\n" +
"with a jump (the server then fails the cast). It fires sooner,\n" +
"about 2 s past the spell's normal cycle, when that is shorter.\n" +
"After a 'too busy' answer nothing is cast until the server answers.\n" +
"0 = never break.");
ImGui.SetNextItemWidth(180);
ImGui.SliderInt("Recovery Retry (ms)", ref _settings.RecoveryRetryMs, 200, 5000);
if (ImGui.IsItemHovered())
ImGui.SetTooltip(
"Heal Self, Stamina to Health, Revitalize and Stamina to Mana refused\n" +
"for 'not enough mana' are tried again after this long: each try\n" +
"rolls Mana Conversion again, and a refusal costs nothing.\n" +
"At most 5 tries a second, 20 in a row.");
ImGui.Checkbox("HP Failsafe Recall", ref _settings.HpFailsafeRecall);
if (ImGui.IsItemHovered())
ImGui.SetTooltip(
"At or under Emergency Heal At with heals failing: break the\n" +
"stuck cast with a jump and heal again; if that fails too,\n" +
"recall to the lifestone.");
ImGui.SetNextItemWidth(180);
ImGui.SliderInt("Attack Spell Delay (ms)", ref _settings.AttackSpellIntervalMs, 0, 5000);
if (ImGui.IsItemHovered())
@ -645,6 +720,10 @@ internal sealed class LegacyAdvancedSettingsUi
ImGui.Separator();
ImGui.Text("Getting Back On Route");
ImGui.Checkbox("Go To Closest Waypoint", ref _settings.NavResumeNearest);
if (ImGui.IsItemHovered())
ImGui.SetTooltip(NavResumeNearestTip);
ImGui.Checkbox("Find A Way Back When Stuck", ref _settings.NavRecoveryEnabled);
if (ImGui.IsItemHovered())
ImGui.SetTooltip("When a jump doesn't free a stuck character, or navigation wanders far off the route, plan a way back to the route around walls and obstacles (the dungeon map indoors, RynthNav outdoors) and open doors on the way. Off = only the jump and side-step escapes, as before.");
@ -756,6 +835,35 @@ internal sealed class LegacyAdvancedSettingsUi
"For servers with buff augments, where your own cast is stronger or\n" +
"lasts longer. On by default: on retail it costs a few extra casts.");
ImGui.Checkbox("Chain buffs on the server's answer", ref _settings.FastBuffChain);
if (ImGui.IsItemHovered())
ImGui.SetTooltip(
"Send the next buff as soon as the server finishes the last one,\n" +
"without waiting for the cast's recoil animation to end.\n" +
"A refused cast turns it off for the rest of that buff pass.\n" +
"On by default. Off = every buff waits for the animation.");
ImGui.Checkbox("Skip buffs this character can't use", ref _settings.SkipUnusableBuffs);
if (ImGui.IsItemHovered())
ImGui.SetTooltip(
"Leave out Blood Drinker / Heart Seeker / Swift Killer when you have no melee or\n" +
"missile weapon (listed or in hand), Spirit Drinker / Hermetic Link when you have no\n" +
"wand, and Defender when you have neither. Masteries for untrained skills are\n" +
"always skipped. On by default. Off = weapon enchantments are cast regardless of\n" +
"listed weapons.");
string skipped = _buffSkips?.Invoke() ?? "";
if (_settings.SkipUnusableBuffs && skipped.Length > 0)
ImGui.TextWrapped("Skipping: " + skipped);
ImGui.Spacing();
if (ImGui.Button("Force Buff##forceBuff") && _forceBuff != null) _forceBuff();
if (ImGui.IsItemHovered())
ImGui.SetTooltip(
"Recast every buff now, whatever time is left on it, starting with\n" +
"Creature Enchantment, Focus, Willpower and Life Magic.\n" +
"Same as /ra buff force (and the FR button).");
ImGui.SameLine();
if (ImGui.Button("Cancel##cancelBuff") && _cancelBuff != null) _cancelBuff();
ImGui.Spacing();
ImGui.Separator();
ImGui.Text("Protections and Banes");
@ -830,9 +938,14 @@ internal sealed class LegacyAdvancedSettingsUi
ImGui.Checkbox("Recover My Corpse", ref _settings.LootOwnCorpse);
if (ImGui.IsItemHovered())
ImGui.SetTooltip("When your own corpse (\"Corpse of <you>\") is within loot range, open it and take\nevery item on it, whatever the loot profile and Loot From say.");
ImGui.Checkbox("Item Info On Select", ref _settings.ItemInfoOnSelect);
ImGui.Checkbox("Item Info On Select", ref _settings.ItemInfoSettings.OnSelect);
if (ImGui.IsItemHovered())
ImGui.SetTooltip("Selecting an item prints its details to chat (/ra iteminfo).");
ImGui.SameLine();
if (ImGui.SmallButton("Options##iiOpts"))
_settings.ItemInfoSettings.ShowWindow = !_settings.ItemInfoSettings.ShowWindow;
if (ImGui.IsItemHovered())
ImGui.SetTooltip("Open the RynthAi Item Info window (fields, ratings, click trigger, layout).");
ImGui.Checkbox("Travel Back To My Corpse", ref _settings.TravelToOwnCorpse);
if (ImGui.IsItemHovered())
ImGui.SetTooltip("After a death, travel back to where you died with RynthNav (outdoors only),\nfighting on the way, recover the corpse, then carry on. Needs the macro running.");
@ -847,6 +960,9 @@ internal sealed class LegacyAdvancedSettingsUi
ImGui.Checkbox("Combine Bags During Salvage", ref _settings.CombineBagsDuringSalvage);
if (ImGui.IsItemHovered())
ImGui.SetTooltip("When salvaging an item, also add any under-full salvage bag of the same material to the salvage panel — the salvage operation merges them into a single bag.");
ImGui.Checkbox("Salvage Without The Panel", ref _settings.SalvageWithoutPanel);
if (ImGui.IsItemHovered())
ImGui.SetTooltip("Salvage (and combine bags) by sending the salvage request to the server directly: AC's salvage panel never opens. A request that changes nothing is tried once through the panel. Needs an engine with plugin API v82.");
ImGui.Spacing();
ImGui.Separator();

Some files were not shown because too many files have changed in this diff Show more